c++ - C++ 中的移位运算符

标签 c++ operators bit-shift

If the value after the shift operator is greater than the number of bits in the left-hand operand, the result is undefined. If the left-hand operand is unsigned, the right shift is a logical shift so the upper bits will be filled with zeros. If the left-hand operand is signed, the right shift may or may not be a logical shift (that is, the behavior is undefined).

谁能解释一下上面几行是什么意思??

最佳答案

这些行的意思并不重要,它们基本上是不正确的。

“如果移位运算符后的值 大于中的位数 左边的操作数,结果是 未定义。”

是真的,但应该说“大于或等于”。 5.8/1:

... the behavior is undefined if the right hand operand is negative, or greater than or equal to the length in bits of the promoted left operand.

未定义的行为意味着“不要做”(见下文)。也就是说,如果 int 在您的系统上是 32 位,那么您不能有效地执行以下任何操作:

int a = 0; // this is OK
a >> 32;   // undefined behavior
a >> -1;   // UB
a << 32;   // UB
a = (0 << 32); // Either UB, or possibly an ill-formed program. I'm not sure.

“如果左侧操作数是无符号的,则右移是逻辑移位,因此高位将填充零。”

这是真的。 5.8/3 说:

If E1 has unsigned type or if E1 has a signed type and a nonnegative value, the result is the integral part of the quotient of E1 divided by the quantity 2 raised to the power E2

如果这对您来说更有意义。 >>1 等同于除以 2,>>2 除以 4,>>3 除以 8,等等。在正值的二进制表示中,除以2相当于将所有位向右移动一位,舍弃最小位,用0填充最大位。

“如果左侧操作数是有符号的,则右移可能是也可能不是逻辑移位(即行为未定义)。”

第一部分是正确的(它可能是也可能不是逻辑转换——它在某些编译器/平台上存在,但在其他编译器/平台上不存在。我认为到目前为止最常见的行为是它不是)。第二部分是错误的,行为不是未定义的。未定义的行为 意味着允许发生任何事情 - 崩溃、从你 Nose 里飞出的恶魔、一个随机值,等等。标准不在乎。在很多情况下,C++ 标准表示行为未定义,但这不是其中之一。

事实上,如果左手操作数是有符号的,并且值为正,那么它的行为与无符号移位相同。

如果左手操作数是有符号的,并且值为负,则结果值是实现定义的。不允许碰撞或着火。实现必须产生结果,实现文档必须包含足够的信息来定义结果。实际上,“实现文档”从编译器文档开始,但这可能会隐式或显式地向您推荐操作系统和/或 CPU 的其他文档。

再次来自标准,5.8/3:

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

关于c++ - C++ 中的移位运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2547789/

相关文章:

c - 位移 x * 数字

c++ - glTexImage2D 访问冲突

c++ - 类中的结构?

c++ - C++ 中的指针否定 (!ptr == NULL)

c - 使用编译器警告捕获常量1的左移溢出?

python - 在 Python 中循环移动(或旋转)数字的数字

C++:2个数组之间的差异

c++ - 在 Linux 中为 c++ 使用 gprof -f 选项

sql - 创建具有左侧/右侧的用户定义运算符

javascript - 为什么 1===1===1 是假的?