C++ 尝试将数字右移 32 会得到两种不同的结果

C++ Trying to shift number right by 32 gives two different results

本文关键字:两种 结果 数字 右移 C++      更新时间:2023-10-16

我正在编写一个小程序以获得一些位操作的经验,我遇到了这种情况。我试图创建一个掩码,将 0 从 MSB 的所有位设置为某个数字 n。当我的 n 为 32 时出现问题。下面是一些演示该问题的代码。

int n = (sizeof(int) * 8) - 0; //Here n is basically set to 32.
    std::cout << n << std::endl; //And indeed, this prints 32.
    //here I expect to see 0 (basically all 32 bits of the number should be 0`s, but I see the opposite, all bits are set to 1.)
    std::cout << ((unsigned) ~0 >> n) << std::endl;
    //And this indeed does what I expected and all 32 bits of the nuber are set to 0`s.
    std::cout << ((unsigned) ~0 >> 32) << std::endl;

我的问题是,既然 n = 32,为什么我在这里看到 2 个不同的结果,而第一个我看到的是 32 s and in the 2nd case, I am seeing 32 0 s?

编辑

:显然这是错误的,原始海报对其进行了测试(谢谢!如果有人有更好的解释,我会把它作为一个想法。


我想你没有考虑过你的类型被投射到什么地方。您可能在 64 位机器上执行此操作,因此 n 是 32 位无符号整数,但数字 32 是 64 位长的整数。

~0成为无符号 int(32 位)

n 是一个 32 位无符号整数

32(可能)是 64 位长

结合~0(32位)和n(32位)可能会给出32位的答案

而将~0(32 位)和32(64 位)结合起来给出 64 位的答案

正如您的问题的评论中所述,将数字移动所有位是一种未定义的行为,但将它们以 64 位整数移动 32 位应该有效!

这是我最好的猜测,我没有测试过。