What method would you use to determine if the the bit that represents 2^x is a 1 or 0 ?
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
In Java the following works fine:
if (value << ~x < 0) {
// xth bit set
} else {
// xth bit not set
}
value
and x
can be int
or long
(and don't need to be the same).
Word of caution for non-Java programmers: the preceding expression works in Java because in that language the bit shift operators apply only to the 5 (or 6, in case of long
) lowest bits of the right hand side operand. This implicitly translates the expression to value << (~x & 31)
(or value << (~x & 63)
if value
is long
).
Javascript: it also works in javascript (like java, only the lowest 5 bits of shift count are applied). In javascript any number
is 32-bit.
Particularly in C, negative shift count invokes undefined behavior, so this test won't necessarily work (though it may, depending on your particular combination of compiler/processor).
Bit shifting right by x and checking the lowest bit.
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
You might want to check out BitSet: http://java.sun.com/javase/6/docs/api/java/util/BitSet.html