Convert Integer into Byte Array (Java)
In Java, converting an Integer to a Byte Array can be achieved using various approaches. One efficient method involves employing the ByteBuffer class:
ByteBuffer b = ByteBuffer.allocate(4); b.putInt(0xAABBCCDD); byte[] result = b.array();
In the code snippet above, the ByteBuffer's byte order is set to BIG_ENDIAN. As a result, result[0] contains the most significant byte (0xAA), followed by result[1] (0xBB), result[2] (0xCC), and result[3] (0xDD).
Alternatively, you can convert the integer manually:
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 provides optimized methods for such tasks. Notably, java.nio.Bits defines helper methods used by ByteBuffer.putInt():
private static byte int3(int x) { return (byte)(x >> 24); } private static byte int2(int x) { return (byte)(x >> 16); } private static byte int1(int x) { return (byte)(x >> 8); } private static byte int0(int x) { return (byte)(x >> 0); }
These methods are designed to extract individual bytes from an integer efficiently.
The above is the detailed content of How to Convert an Integer to a Byte Array in Java?. For more information, please follow other related articles on the PHP Chinese website!