How to take bit number 3 from 8 bits

久未见 提交于 2019-12-23 18:23:18

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!