Wingdom
Wingdom

Reputation: 449

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?

Upvotes: 13

Views: 22930

Answers (3)

user12042
user12042

Reputation: 235

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.

Upvotes: 3

Ted Hopp
Ted Hopp

Reputation: 234857

This should work for all non-negative N < 33 32:

x & ((1 << N) - 1)

It's worth elaborating on how this works for N == 31 and N == 32. For N == 31, we get 1 << N == Integer.MIN_VALUE. When you subtract 1 from that, Java silently wraps around to Integer.MAX_VALUE, which is exactly what you need. For N == 32, the 1 bit is shifted completely out, so 1 << N == 0; then (1 << N) - 1 == -1, which is all 32 bits set.

For N == 32, this unfortunately doesn't work because (thanks, @zstring!) the << operator only shifts by the right side mod 32. Instead, if you want to avoid testing for that case specially, you could use:

x & ((int)(1L << N) - 1)

By shifting a long, you get the full 32-bit shift, which, after casting back to an int, gets you 0. Subtracting 1 gives you -1 and x & -1 is just x for any int value x (and x is the value of the lower 32 bits of x).

Upvotes: 15

Peter Lawrey
Peter Lawrey

Reputation: 533920

Ted's approach is likely to be faster but here is another approach

x << -N >>> -N

This shift all the bit up and then down to chop off the top bits.

int i = -1;
System.out.println(Integer.toBinaryString(i));
i = i << -5 >>> -5;
System.out.println(Integer.toBinaryString(i));

prints

11111111111111111111111111111111
11111

Upvotes: 4

Related Questions