简体   繁体   English

C中逻辑或的按位移位

[英]bitwise shift with logical OR in C

My original code to take x and turn it into the largest negative int was 我原来的代码将x转换为最大的负整数是

*x = 1 <<31 | ~ 1<<31;

which works but when I tried just using 哪个有效,但是当我尝试仅使用

*x = 1 <<31;

It returned the same answer can someone explain why this is so? 它返回了相同的答案,有人可以解释为什么会这样吗?

If your int is on 32 bits on your architecture, the largest negative int value is obviously 0x80000000. 如果int在体系结构的32位上,则最大的负int值显然是0x80000000。
Let's look at your code and add parenthesis to show the precedence of operators (this is the key here): 让我们看一下代码并添加括号以显示运算符的优先级(这是此处的关键):

*x = 1 <<31 | ~ 1<<31 = (1 << 31) | ((~1) << 31)

The evaluation of the expression ((~1) << 31) gives the result 0x00000000. 表达式((~1) << 31)的计算结果为0x00000000。
So the final result is 1 << 31 = 0x80000000 . 所以最终结果是1 << 31 = 0x80000000

Well if you know two's complement, then you know that for a 32 bit integer, 0x80000000 must be the largest negative value, because if you flip the bits and add one from 0x80000000, you get 0x7fffffff. 好吧,如果您知道二进制补码,那么您知道对于32位整数,0x80000000必须是最大的负值,因为如果翻转这些位并从0x80000000加一个,则得到0x7fffffff。 add one and you get 0x80000000, the largest negative number possible with 32 bits. 加一,您将得到0x80000000,这是32位可能的最大负数。 This has a 1 in the MSB, and there is no way to get larger than this, given that the initial number needs to save a bit for the sign. 它的最高有效位(MSB)为1,鉴于初始数字需要为符号节省一点,因此没有办法使该数值更大。 Your original code just fills the int with 1's and then shifts over 31 resulting in the same final value as *x = 1 <<31; 您的原始代码只是将int填充为1,然后移至31,最终结果与* x = 1 << 31;相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM