views:

1177

answers:

4

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?? :D

thnx!

A: 
integer & 0xFF

for the first byte

(integer >> 8) & 0xFF

for the second and loop etc., writing into a preallocated byte array. A bit messy, unfortunately.

Brian Agnew
+3  A: 

How about:

public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

The idea is not mine. I've taken it from some post on dzone.com.

Grzegorz Oledzki
-1 Not a good idea to hand-code things like this; that's what properly-tested and reviewed JDK libraries are for.
Kevin Bourrillion
I see your point, but for this particular task 'my' code is more declarative and clear than some 'magic' ByteBuffer, which one has to check to see what it does.
Grzegorz Oledzki
A: 
byte[] conv = new byte[4];
conv[3] = (byte) input & 0xff;
input >>= 8;
conv[2] = (byte) input & 0xff;
input >>= 8;
conv[1] = (byte) input & 0xff;
input >>= 8;
conv[0] = (byte) input;
Carl Smotricz
+9  A: 

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 
dfa