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/58708773/

相关文章:

c++ - 重印二维数组素因子

c - C 中的移位运算符前置一个而不是零

algorithm - 16、32 或 64 位处理器执行多少个原始操作来执行 N 位二进制数的逻辑右移?

assembly - 如何在汇编中使用 ADD 而不是使用 SHL 左移?

c++ - 使用 vector 和 pthreads 的不一致计数

c++ - 临界区队列

c++ - 不能在 Boost.Asio 中使用可移动物体

javascript - 伪代码中的 "!"是什么意思?我知道 "!"代表阶乘,但我无法翻译它

c# - 我需要有关 C# 运算符的帮助

c# - 使用 if 语句将组合框值与两个文本框值进行比较