0

How can I convert an integer between 0 and 65k to fixed length of two bytes? as an example

2 would be 00000000 00000010

~65k would be 11111111 11111111

and all that in a byte array

1
  • I edited my answer Commented Mar 8, 2017 at 13:39

2 Answers 2

1

java has the short data type, this is a 2 bytes integer. You cast the integer to short.

int a = 1;
short b = (short)a;

If you want the bytes of the integer you can use ByteBuffer

byte[] bytes = ByteBuffer.allocate(2).putShort((short)intnumber).array();

Or if you want the binary format you can just use toBinaryString method of the Integer.

int x = 2;
System.out.println(Integer.toBinaryString(x));
Sign up to request clarification or add additional context in comments.

2 Comments

I think the middle one is what I'm looking for, but it throws an BufferOverflow Exception in my case
Yes, Just use ByteBuffer.allocate(2).putShort((short)1);
0

When x is your number between 0 and 65,535 just use

new byte[] { (byte) (x >> 8), (byte) x }

to create a byte array containing the value as two bytes in big-endian format.

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.