为什么(1 <<;&下; 31)&GT;&GT; 31结果-1? [英] Why does (1 << 31) >> 31 result in -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 $ presentable结果C $ C>类型。从标准:
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 theint
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屋!