Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get two lower bytes from int variable

I have some data in int variables in Java (range between 0 and 64000). How to convert to byte this integer? I need just two lower bytes from int (range is ok). How to extract this?

like image 610
Damir Avatar asked Jan 28 '11 09:01

Damir


1 Answers

You can get the lowest byte from the integer by ANDing with 0xFF:

byte lowByte = (byte)(value & 0xFF);

This works because 0xFF has zero bits everywhere above the first byte.

To get the second-lowest-byte, you can repeat this trick after shifting down all the bits in the number 8 spots:

byte penultimateByte = (byte)((value >> 8) & 0xFF);
like image 56
templatetypedef Avatar answered Oct 13 '22 03:10

templatetypedef