python check if bit in sequence is true or false

こ雲淡風輕ζ 提交于 2019-12-01 08:50:52

Without the slow byte shifting:

if bits & 0b1000:
    ...

EDIT: Actually, (1 << 3) is optimized out by the compiler.

>>> dis.dis(lambda x: x & (1 << 3))
  1           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               3 (8)
              6 BINARY_AND          
              7 RETURN_VALUE        
>>> dis.dis(lambda x: x & 0b1000)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               1 (8)
              6 BINARY_AND          
              7 RETURN_VALUE    

The two solutions are equivalent, choose the one that looks more readable in your context.

You can use bit shifting

>>> 0b10010101 >> 4 & 1
1
>>> 0b10010101 >> 3 & 1
0
bits = 0b11010011

if bits & (1 << 3):
    ...

Bitwise left-shifting and bitwise AND operator is your friend. In general you can check if the nth bit is set/unset as below:

if (x & (1<<n)) 
  ## n-th bit is set (1)

else 
  ## n-th bit is not set (0)
bits = '1110111'

if bits[-4] == '0':
    print "......false"
else:
    print  "....true"

Assuming integers, if you are counting Left Hand (LH), Most Significant Bit (MSB) to the Right Hand (RH) Lease Significant Bit (LSB):

def check_bitL2R(byte, bit):
    return bool(byte & (0b10000000>>bit))

Reverse if you want to count LSB towards the MSB:

def check_bitR2L(byte, bit):
    return bool(byte & (0b1<<bit))

Then check that:

fmt='{:^5} {:^5} {:^5}'
print fmt.format(*'bit  LSB  MSB'.split())
for bit in range(8):
    print fmt.format(bit, check_bitR2L(0b10010101, bit), check_bitL2R(0b10010101, bit)) 

Prints:

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