2

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.

Community
  • 1
  • 1
jim
  • 7,748
  • 11
  • 71
  • 144

2 Answers2

2

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),
  };
}
Mike Samuel
  • 109,453
  • 27
  • 204
  • 234
0
// 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);
arc
  • 584
  • 2
  • 5