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).