Reputation: 7680
Is there a fast way to get the last bit of an integer in Java. Can be both the bit at position 5 or an integer with only the 5'th bit.
65 -> 64
11 -> 8
13 -> 8
No negative numbers
It's a wording issue it's not the last bit but highest bit.
Upvotes: 1
Views: 1365
Reputation: 109547
Dive in the javadoc, always worth it: Integer.highestOneBit.
assert 64 == Integer.highestOneBit(65);
assert 2 == Integer.bitCount(65);
assert 6 == 31 - Integer.numberOfLeadingZeros(65);
There is also numberOfTrailingZeros
and so on.
Upvotes: 5
Reputation: 62864
You can use the Integer.toBinaryString()
method, which will give you a string representation of the integer argument as an unsigned integer in base 2.
String binary = Integer.toBinaryString(value);
char lastBit = binary.charAt(0);
Upvotes: 1