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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This should work for all non-negative N <
3332:It’s worth elaborating on how this works for
N == 31and. ForN == 32N == 31, we get1 << N == Integer.MIN_VALUE. When you subtract 1 from that, Java silently wraps around toInteger.MAX_VALUE, which is exactly what you need.ForN == 32, the 1 bit is shifted completely out, so1 << 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:By shifting a
long, you get the full 32-bit shift, which, after casting back to anint, gets you 0. Subtracting 1 gives you -1 andx & -1is justxfor anyintvaluex(andxis the value of the lower 32 bits ofx).