python检查顺序位是对还是错 [英] python check if bit in sequence is true or false

查看:89
本文介绍了python检查顺序位是对还是错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确定序列中的某个位是1还是0(对还是错) 如果我有一些位序列11010011,如何检查第4位是True还是False?

I want to find if a bit in a sequense is 1 or 0 (true or false) if i have some bitsequense of 11010011, how can i check if the 4th position is True or False?

示例:

10010101 (4th bit) -> False
10010101 (3rd bit) -> True

推荐答案

不作任何改动:

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.

这篇关于python检查顺序位是对还是错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆