vote up 4 vote down star
1

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!

flag

4 Answers

vote up 9 vote down check

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 
link|flag
vote up 3 vote down

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.

link|flag
-1 Not a good idea to hand-code things like this; that's what properly-tested and reviewed JDK libraries are for. – Kevin Bourrillion Feb 2 at 15:33
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. – GrzegorzOledzki Feb 2 at 20:50
vote up -1 vote down
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.

link|flag
vote up -1 vote down
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;
link|flag

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.