3

I am trying to convert an int into three bytes representing that int (big endian).

I'm sure it has something to do with bit-wise and and bit shifting. But I have no idea how to go about doing it.

For example:

int myInt; // some code byte b1, b2 , b3; // b1 is most significant, then b2 then b3. 

*Note, I am aware that an int is 4 bytes and the three bytes have a chance of over/underflowing.

5 Answers 5

15

To get the least significant byte:

b3 = myInt & 0xFF; 

The 2nd least significant byte:

b2 = (myInt >> 8) & 0xFF; 

And the 3rd least significant byte:

b1 = (myInt >> 16) & 0xFF; 

Explanation:

Bitwise ANDing a value with 0xFF (11111111 in binary) will return the least significant 8 bits (bits 0 to 7) in that number. Shifting the number to the right 8 times puts bits 8 to 15 into bit positions 0 to 7 so ANDing with 0xFF will return the second byte. Similarly, shifting the number to the right 16 times puts bits 16 to 23 into bit positions 0 to 7 so ANDing with 0xFF returns the 3rd byte.

Sign up to request clarification or add additional context in comments.

Comments

3
byte b1 = (myint >> 16) & 0xff; byte b2 = (myint >> 8) & 0xff; byte b3 = myint & 0xff; 

I am unsure how this holfds in java though, i aam not a java dev

1 Comment

Actually you need an explicit cast from int to byte, and then the & 0xff is unnecessary (and bytes are signed, unlike C#).
2

An int doesn't fit into 3 bytes. However, assuming that you know these particular ones do:

 byte b1 = (myInt & 0xff); myInt >>= 8; byte b2 = (myInt & 0xff); myInt >>= 8; byte b3 = (myInt & 0xff); 

2 Comments

You've got the most/least significant order reversed.
There's no need to modify myInt unnecessarily, as shown in other answers.
2

In Java

int myInt = 1; byte b1,b2,b3; b3 = (byte)(myInt & 0xFF); b2 = (byte)((myInt >> 8) & 0xFF); b1 = (byte)((myInt >> 16) & 0xFF); System.out.println(b1+" "+b2+" "+b3); 

outputs 0 0 1

Comments

0

The answer of Jeremy is correct in case of positive integer value. If the conversion should be correct for negative values, it is little more complicated due to two's-complement format (https://en.wikipedia.org/wiki/Two%27s_complement). The trick is to remove the gap between the interesting bits (the less significant bits) and the 'sign' bit. One easy method is multiplication of the number.

 int myIntMultiplied = myInt * 256; byte b1, b2, b3; b3 = (byte) ((myIntMultiplied >> 8) & 0xFF); b2 = (byte) ((myIntMultiplied >> 16) & 0xFF); b1 = (byte) ((myIntMultiplied >> 24) & 0xFF); 

This will end up with correct two's-complement format for negative values.

PS: You can check and compare binary representation this way:

Integer.toBinaryString(myInt); Integer.toBinaryString(myIntMultiplied ); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.