且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python检查顺序位是对还是错

更新时间:2023-11-25 23:01:52

不作任何改动:

if bits & 0b1000:
    ...

编辑:实际上,(1 << 3)是由编译器优化的.

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.