逻辑与按位

发布于 2024-12-20 01:23:24 字数 107 浏览 0 评论 0原文

逻辑运算符andor与按位运算符&|在使用上有何不同?各种解决方案的效率是否有差异?

What the different between logical operators and, or and bitwise analogs &, | in usage? Is there any difference in efficiency in various solutions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

对岸观火 2024-12-27 01:23:24

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

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

Logical operators operate on logical values, while bitwise operators operate on integer bits. Stop thinking about performance, and use them for they're meant for.

if x and y: # logical operation
   ...
z = z & 0xFF # bitwise operation
蓝戈者 2024-12-27 01:23:24

按位 = 逐位检查

# Example

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

逻辑 = 逻辑检查,换句话说,您可以说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) 

Bitwise = Bit by bit checking

# Example

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

Logical = Logical checking or in other words, you can say True/False checking

# 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) 
山川志 2024-12-27 01:23:24

逻辑运算符用于布尔值,因为 true 等于 1,false 等于 0。如果您使用 1 和 0 以外的(二进制)数字,则任何非零的数字都将变为一个。
例如: int x = 5; (二进制为 101) int y = 0; (二进制为 0) 在这种情况下,打印 x & & y 将打印 0,因为 101 变为 1,而 0 保持为零:这与打印 true && 相同。 false,返回 false (0)。

另一方面,按位运算符对两个操作数的每一位执行运算(因此称为“按位”)。
例如:int x = 5; int y = 8; 打印 x | y(按位或)将计算:
000101 (5)
| 1000 (8)
-----------
= 1101 (13)
意味着它将打印 13.

Logical operators are used for booleans, since true equals 1 and false equals 0. If you use (binary) numbers other than 1 and 0, then any number that's not zero becomes a one.
Ex: int x = 5; (101 in binary) int y = 0; (0 in binary) In this case, printing x && y would print 0, because 101 was changed to 1, and 0 was kept at zero: this is the same as printing true && false, which returns false (0).

On the other hand, bitwise operators perform an operation on every single bit of the two operands (hence the term "bitwise").
Ex: int x = 5; int y = 8; printing x | y (bitwise OR) would calculate this:
000101 (5)
| 1000 (8)
-----------
= 1101 (13)
Meaning it would print 13.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文