I'm trying to find the least significant 6 bits of a 16 bit integer. Let's say my integer is 139 / 0x008B.
>>> "{0:b}".format(139)
'10001011'
So the least significant 6 bits are:
'001011'
>>> int('001011', 2)
11
However, I thought I could do this with the >> operator, but that isn't giving me what I expect:
>>> 139 >> 6
2
Can someone explain the difference between these two?
Shifts are for re-positioning bits, not for isolating them. This is called "masking", and in your case you need a bitmask that you "and" with your number. This is done with the &-operator in Python. It's fundamentally different from the logical "and"-operator, so don't confuse them!
>>> bin(139 & 0b111111)
'0b1011'
I think you might want to use the bit-wise 'and' operator ( &
) and not the right-shift operator ( >>
).
Try the following: 139 & 0b111111
That should give you the 6 least-significant bits.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.