stefan stefan - 6 months ago 28
Java Question

Java integer to byte array

I got an integer:

1695609641


when I use method:

String hex = Integer.toHexString(1695609641);
system.out.println(hex);


gives:

6510f329


but I want a byte array:

byte[] bytearray = new byte[] { (byte) 0x65, (byte)0x10, (byte)0xf3, (byte)0x29};


How can I make this?

dfa dfa
Answer

using Java NIO's ByteBuffer is very simple:

byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

output:

0x65 0x10 0xf3 0x29 
Comments