逻辑与按位
逻辑运算符and
、or
与按位运算符&
、|
在使用上有何不同?各种解决方案的效率是否有差异?
What the different between logical operators and
, or
and bitwise analogs &
, |
in usage? Is there any difference in efficiency in various solutions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
逻辑运算符对逻辑值进行运算,而按位运算符对整数位进行运算。停止考虑性能,并根据它们的用途使用它们。
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.
按位 = 逐位检查
逻辑 = 逻辑检查,换句话说,您可以说
True/False
检查Bitwise = Bit by bit checking
Logical = Logical checking or in other words, you can say
True/False
checking逻辑运算符用于布尔值,因为
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
(按位或)将计算:00
0101
(5)| 1000
(8)-----------
= 1101
(13)意味着它将打印
13.
Logical operators are used for booleans, since
true
equals 1 andfalse
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, printingx && y
would print0
, because 101 was changed to 1, and 0 was kept at zero: this is the same as printingtrue && false
, which returnsfalse
(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;
printingx | y
(bitwise OR) would calculate this:00
0101
(5)| 1000
(8)-----------
= 1101
(13)Meaning it would print
13
.