Converting an Integer to a Byte Array in Java
To convert an integer into a byte array efficiently, consider using Java's ByteBuffer class.
ByteBuffer b = ByteBuffer.allocate(4); b.putInt(0xAABBCCDD); byte[] result = b.array();
This ensures that result[0] contains the highest byte (0xAA), while result[3] contains the lowest byte (0xDD).
Alternatively, you can perform the conversion manually:
public static byte[] toBytes(int i) { byte[] result = new byte[4]; result[0] = (byte) (i >>> 24); result[1] = (byte) (i >>> 16); result[2] = (byte) (i >>> 8); result[3] = (byte) i; return result; }
The ByteBuffer class offers helper methods, like int3(), for performing these operations more efficiently:
private static byte int3(int x) { return (byte) (x >>> 24); }
The above is the detailed content of How to Efficiently Convert an Integer to a Byte Array in Java?. For more information, please follow other related articles on the PHP Chinese website!