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
For the
n
th LSB (least significant bit), the following should work:I coded a little static class which is doing some of the bit operation stuff.
If there are some questions flying around, just write me an email.
Good Programming!
I wonder if:
.. 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
My contribution - ignore previous one
You can also use
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 equivalentdeclare a temp int and make it equal the original. then shift temp >> x times, so that the bit you want to check is at the last position. then do temp & 0xf to drop the preceding bits. Now left with last bit. Finally do if (y & 1 == 0), if last bit is a 1, that should equal 0, else will equal 1. Its either that or if (y+0x1 == 0)... not too sure. fool around and see