Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get n Least Significant Bits from an Int

This seems fairly straightforward, but I cant find an answer. If I have an int X, what is the best way to get N least significant bits from this int, in Java?

like image 227
Wingdom Avatar asked Oct 07 '12 06:10

Wingdom


1 Answers

You can also use a mask. If you use the & bitwise operator you can then remove whatever bit you would want to remove (say the highest x bits);

int mask = 0x7FFFFFFF                 //Example mask where you will remove the 
                                      // most significant bit 
                                      // (0x7 = 0111b and 0xF = 1111b).
int result = numberToProcess & mask;  //And apply the mask with the &bitwise op.

The disadvantage to this is that you will need to make a mask for each bit, so perhaps this is better seen as another method of approach in general.

like image 168
user12042 Avatar answered Oct 02 '22 22:10

user12042