问题
I have this in hex: 08
Which is this in binary: 0000 1000
(bit positions: 7,6,5,4,3,2,1,0)
Now I would like to make a bitmask in python, so I have bit position 3.
Here in example 1
or better (the one in ""): 0000 "1"000
What shall I do to have only this bit?
Thanks
回答1:
Shift right by the bit index to have that bit in the 0th position, then AND with 1 to isolate it.
val = 0b01001000 # note the extra `1` to prove this works
pos = 3
bit = (val >> pos) & 1
print(bit)
outputs 1
回答2:
you could just do this:
def get_bit(n, pos):
return (n >> pos) & 1
res = get_bit(n=8, pos=3)
# 1
shift the number n
left by pos
bits (>> pos
) and then mask away the rest (& 1
).
the doc on Bitwise Operations on Integer Types may help.
来源:https://stackoverflow.com/questions/56018322/how-to-take-bit-number-3-from-8-bits