[英]the difference between a | b and a + b when a or b is zero
I am trying to implement an if statement in C using bit manipulation. 我正在尝试使用位操作在C中实现if语句。 the following code seems to work:
以下代码似乎有效:
// if (x) then y else z
int conditional(int x, int y, int z) {
int v = (!!x); //v is 1 or 0
return ((v<<31)>>31)&y | ((~v<<31)>>31)&z;
}
however, when I replace "|" 但是,当我替换“ |”时 with "+" in the last line, the code fails when x = 0x80000000,y = 0x80000000,z = 0x7fffffff.
最后一行带有“ +”,则当x = 0x80000000,y = 0x80000000,z = 0x7fffffff时,代码将失败。 It returns 0 instead of 0x80000000.
它返回0而不是0x80000000。
so my question is: why does the following fail? 所以我的问题是:为什么以下失败? thanks!
谢谢!
((v<<31)>>31)&y + ((~v<<31)>>31)&z
edit: I understand that | 编辑:我了解 is bitwise OR and + is addition.
是按位或,而+是加法。 but in this case, v is either 1 or zero, so (v<<31)>>31) is either all ones or all zeros.
但是在这种情况下,v为1或零,因此(v << 31)>> 31)要么全为1,要么全为零。 y |
y | 0x00000000 should be the same as y + 0x00000000, right?
0x00000000应该和y + 0x00000000一样,对吗? specifically, v is 1. so the result with the above input should be y, but returns 0 when "+" is used.
具体来说,v为1,因此上述输入的结果应为y,但使用“ +”时返回0。
I am afraid we have to use math. 恐怕我们必须使用数学。
The highest bits of your variables are set, thus doubling equals a bitshift of 1 left, which equals an overflow. 变量的最高位被设置,因此加倍等于左移1位,这等于溢出。 All remaining bits are 0. Thus you get 0 as result.
其余所有位均为0。因此,结果为0。
Keep in mind that |
请记住
|
is a bitwise ||
是按位
||
and does not carry over values to other binary digits. 并且不会将值保留到其他二进制数字。
+
does. +
做。
So speaking, if a
and b
are orthogonal base
functions/vectors of your bitvectorspace (which in your case is not true) a|b
and a+b
are equal – but only then. 因此,如果
a
和b
是您的位向量空间的orthogonal base
函数/向量(在您的情况下不成立), a|b
和a+b
是相等的-但只有那时是相等的。
Update: 更新:
The root cause here is operator precedence: (decreasing order) +
&
|
根本原因是运算符优先级:(降序)
+
&
|
. 。
So 所以
((v<<31)>>31)&y + ((~v<<31)>>31)&z
becomes 变成
((v<<31)>>31) & (y + ((~v<<31)>>31)) & z
In binary, 10+01 = 11 and 10 | 以二进制形式,10 + 01 = 11和10 | 01 = 11. But 10 + 10 = 100, and 10 |
01 =11。但是10 + 10 = 100,而10 | 10 = 10.
10 = 10。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.