对位移位行为的质疑

Doubts on bit-shifting behavior

我想澄清一些关于位移位的疑惑:

  1. 使用unsigned int:

    unsigned int i = 500;
    i << 24;

    据我所知,这会导致 unsigned int 溢出,这完全没问题吗?

C++17 (8.5.7/2) - The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 × 2^E2, reduced modulo one more than the maximum value representable in the result type.

  1. signed int 上使用右移非常好,只要我的移动小于“32 位”,因为 'int' 在我的平台上是 32 位。

    int i = 500;
    i >> 31;

是否溢出?

C++17 (8.5.7/3) The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a non-negative value, the value of the result is the integral part of the quotient of E1/2^E2.

  1. is this perfectly fine?

    是的。 i 将变为 4093640704,十六进制 0xf4000000

  2. Is that an overflow?

    没有。是右移(division-like运算),所以i会变成零。

请注意,关于轮班的规则很可能会改变。目前,有几种情况是未定义的行为或定义的实现。由于下一个标准将需要二进制补码算法,关于移位的规则将放宽:唯一未定义的行为是,如果移位量大于或等于类型的宽度。以下是当前的规则草案:link.