逻辑运算符与按位运算符的区别是什么 [英] What's the point of logical operators vs. bitwise operators

查看:91
本文介绍了逻辑运算符与按位运算符的区别是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此声明是合乎逻辑的操作

Given this statement is a logical operation

 ((a > 5) && (b > 4))

此语句是按位操作

   ((a > 5) & (b > 4)) 

以上两个语句不相等.

因为(a> 5) {0,1}

那么,为什么我们需要逻辑运算符& ;?按位操作?

So, why do we need logical operators & bitwise-operation?

编辑:感谢您的所有反馈.关于逻辑运算符的短路行为,我实际上不希望这种行为-我正在为GPU编写代码,其中分支降低了性能:短路导致两个分支而不是代码中的一个分支.

Edit: thanks for all of the feedback. Regarding the short circuit behaviour of logical operators, I actually do not want this behaviour - I am writing code for a GPU where branches degrade performance: short circuit results in two branches instead of one in the code.

对于用C进行的数值比较,在不需要短路的情况下,似乎逻辑和按位行为具有相同的行为.就我而言,按位运算比逻辑运算要快.

For numerical comparisons in C, in the case where short circuit is not needed, it seems that logical and bitwise have identical behaviour. In my case, bitwise ops are faster than logical.

对于没有在原始帖子中添加这些详细信息,我深表歉意.

I apologize for not putting these details in the original posting.

推荐答案

我认为不,请举这个例子(0b-表示二进制):

I think no, take this example (0b - means binary):

a = 0b00000010
b = 0b00000100

现在, a b 都不为0.但是 a&b == 0 (由于按位AND的定义方式).

Now, neither a nor b is 0. But a & b == 0 (due to the way bitwise AND is defined).

但是 a&&b!= 0 (因为如果至少一个操作数为0,则逻辑AND结果为0-上面的 a b 则不是这种情况).

However a && b != 0 (because for logical AND result is 0 if at least one operand is 0 - this is not the case with a and b above).

还有短路评估,如果在&& 中左操作数为0,则不会对右一进行评估,因为结果肯定为0(例如,如前所述 0&& x == 0 ,无论 x 的值如何.)

Also there is short circuit evaluation, if in && left operand is 0, the right one will not be evaluated because result is certainly 0 (e.g., as already mentioned 0 && x == 0 no matter value of x).

这篇关于逻辑运算符与按位运算符的区别是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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