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.

1
  • What endianness do you want? Commented Mar 6, 2012 at 16:21

2 Answers 2

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),
  };
}
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.