逻辑与按位

新手上路,请多包涵

What the different between logical operators and , or and bitwise analogs & , | in usage?各种解决方案在效率上有什么区别吗?

原文由 I159 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 341
2 个回答

逻辑运算符对逻辑值进行运算,而按位运算符对整数位进行运算。停止考虑性能,并根据它们的用途使用它们。

 if x and y: # logical operation
   ...
z = z & 0xFF # bitwise operation

原文由 Cat Plus Plus 发布,翻译遵循 CC BY-SA 3.0 许可协议

Bitwise = 逐位检查

# Example

Bitwise AND: 1011 & 0101 = 0001
Bitwise OR: 1011 | 0101 = 1111

Logical = 逻辑检查或者换句话说,你可以说 True/False 检查

# Example

# both are non-zero so the result is True
Logical AND: 1011 && 0101 = 1 (True)

# one number is zero so the result is False
Logical AND: 1011 && 0000 = 0 (False)

# one number is non-zero so the result is non-zero which is True
Logical OR: 1011 || 0000 = 1 (True)

# both numbers are zero so the result is zero which is False
Logical OR: 0000 || 0000 = 0 (False)

原文由 Abu Shoeb 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题