What method would you use to determine if the the bit that represents 2^x is a 1 or 0 ?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Bit shifting right by x and checking the lowest bit.
Another alternative:
You might want to check out BitSet: http://java.sun.com/javase/6/docs/api/java/util/BitSet.html
If someone is not very comfortable with bitwise operators, then below code can be tried to programatically decide it. There are two ways.
1) Use java language functionality to get the binary format string and then check character at specific position
2) Keep dividing by 2 and decide the bit value at certain position.
Output
In Java the following works fine:
value
andx
can beint
orlong
(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 tovalue << (~x & 31)
(orvalue << (~x & 63)
ifvalue
islong
).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).
I'd use:
(You may be able to get away with fewer brackets, but I never remember the precedence of bitwise operations.)