I've found this solution but it seems to be for Java SE. I can't find an alternative to the System.out.format() function. Also, I have changed the ByteBuffer.allocate() function to ByteBuffer.allocateDirect() is this correct?

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

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

Thank you.

link|improve this question

What endianness do you want? – Mike Samuel Mar 6 at 16:21
feedback

2 Answers

up vote 2 down vote accepted

If you want network byte order aka big-endian order which is used throughout Java's serialization and remoting libraries:

static byte[] intToBytesBigEndian(int i) {
  return new byte[] {
    (byte) ((i >>> 24) & 0xff),
    (byte) ((i >>> 16) & 0xff),
    (byte) ((i >>> 8) & 0xff),
    (byte) (i & 0xff),
  };
}
link|improve this answer
feedback
// 32-bit integer = 4 bytes (8 bits each)
int i = 1695609641;
byte[] bytes = new byte[4];

// big-endian, store most significant byte in byte 0
byte[3] = (byte)(i & 0xff);
i >>= 8;
byte[2] = (byte)(i & 0xff);
i >>= 8;
byte[1] = (byte)(i & 0xff);
i >>= 8;
byte[0] = (byte)(i & 0xff);
link|improve this answer
fixed with explicit cast – arc Mar 6 at 16:27
feedback

Your Answer

 
or
required, but never shown

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