Given that : 0000000000000000000000000000000000000000000000000000000000000001 = 1
What method would you use to determine if the the bit that represents 2^x is a 1 or 0 ?
Given that : 0000000000000000000000000000000000000000000000000000000000000001 = 1
What method would you use to determine if the the bit that represents 2^x is a 1 or 0 ?
I'd use:
if ((value & (1L << x)) != 0)
{
// The bit was set
}
(You may be able to get away with fewer brackets, but I never remember the precedence of bitwise operations.)
For the n
th LSB (least significant bit), the following should work:
bool isSet = (value & (1 << n)) != 0;
You can also use
bool isSet = ((value>>x) & 1) != 0;
EDIT: the difference between "(value>>x) & 1
" and "value & (1<<x)
" relies on the behavior when x is greater than the size of the type of "value" (32 in your case).
In that particular case, with "(value>>x) & 1
" you will have the sign of value, whereas you get a 0 with "value & (1<<x)
" (it is sometimes useful to get the bit sign if x is too large).
If you prefer to have a 0 in that case, you can use the ">>>
" operator, instead if ">>
"
So, "((value>>>x) & 1) != 0
" and "(value & (1<<x)) != 0
" are completely equivalent
Another alternative:
if (BigInteger.valueOf(value).testBit(x)) {
// ...
}
I wonder if:
if (((value >>> x) & 1) != 0) {
}
.. is better because it doesn't matter whether value is long or not, or if its worse because it's less obvious.
Tom Hawtin - tackline Jul 7 at 14:16
You might want to check out BitSet: http://java.sun.com/javase/6/docs/api/java/util/BitSet.html