为什么(1 <<;&下; 31)&GT;&GT; 31结果-1? [英] Why does (1 &lt;&lt; 31) &gt;&gt; 31 result in -1?

查看:177
本文介绍了为什么(1 <<;&下; 31)&GT;&GT; 31结果-1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  INT Z = 1;
z,其中;&LT = 31;
ž&GT;&GT; = 31;
的printf(%d个\\ N,Z);

当我运行code, Z = -1 ,为什么?


解决方案

  INT Z = 1;
z,其中;&LT = 31;

假设 INT 为32位和二的补用重新presentation,左移是不确定的行为的 C ,因为如果不重新在 INT 类型。从标准:


  

E1 1所述的结果;&LT; E2 E1 左移 E2 位的位置


  
  

...


  
  

如果 E1 有符号类型和非负值,和 E1×2 E2 重新presentable的结果类型,然后就是
  所得到的值;否则,行为是不确定的。


在实践中,它很可能会导致在 0x80000000的,这是作为一个负数处理

和右移的的整数是实现定义的:


  

E1 >> E2 E1 右移 E2 位位置的结果。


  
  

...


  
  

如果 E1 有一个签署类型和负值,结果值是实现定义的。



C ++ 左移以类似的方式定义,直到 C ++ 14 ,为的 @TC 提到(或具有某些限制,可能会连到 C ++ 11 ,为的 @MattMcNabb 写)。

但是,即使左移被定义和为0x8000000 是预期的值,负数的右移的结果仍然是实现定义

int z = 1;
z <<= 31;
z >>= 31;
printf ("%d\n",z);

When I run the code, z=-1, why?

解决方案

int z = 1;
z <<= 31;

Assuming int is 32 bit and two's complement representation is used, the left shift is undefined behavior in C because the result if not representable in the int type. From the standard:

The result of E1 << E2 is E1 left-shifted E2 bit positions

...

If E1 has a signed type and nonnegative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

In practice, it is likely to result in 0x80000000, which is treated as a negative number.

And right-shifting of negative integers is implementation-defined behavior:

The result of E1 >> E2 is E1 right-shifted E2 bit positions.

...

If E1 has a signed type and a negative value, the resulting value is implementation-defined.


In C++ left shift is defined in a similar way till C++14, as @T.C. mentioned (or, with some restrictions, might be even till C++11, as @MattMcNabb wrote).

But even if left-shift is defined and 0x8000000 is the expected value, the result of a right shift of a negative number is still implementation-defined.

这篇关于为什么(1 <<;&下; 31)&GT;&GT; 31结果-1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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