C++ 尝试将数字右移 32 会得到两种不同的结果
C++ Trying to shift number right by 32 gives two different results
我正在编写一个小程序以获得一些位操作的经验,我遇到了这种情况。我试图创建一个掩码,将 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 位应该有效!
这是我最好的猜测,我没有测试过。
相关文章:
- 在C++中将函数压缩为两种方式
- 如何使映射键具有两种不同的数据类型?
- 两种访问I2C总线的方法有什么区别?
- 两种模板示例有什么区别?
- 如何构造可以调用和返回两种不同类型的模板
- 这两种C++语法之间有什么区别?
- 为什么两种不同的对象初始化方式给出不同的输出
- std::cin 从控制台获取两种不同的变量类型,'storing'以后使用第二种类型?
- 定义类模板构造函数的两种方法之间的区别
- 初始化类的两种方法?
- C++ 一个函数,可以根据接受的值返回两种类型之一
- 如何检查程序员在C++中提供的两种不同格式的输入
- C++指针中的这两种类型的值分配有什么区别?
- 如何在c ++中以一行(水平)打印两个文件的数据?如给定的.这两种形式来自两个不同的文本文件
- 如何获得将两种不同类型的相乘的结果类型?
- 使用两种不同的方法遍历 Vector 的结果不一致
- C++ 尝试将数字右移 32 会得到两种不同的结果
- 如何根据两种输入状态编写输出结果
- 用两种不同的方式初始化指针会得到两种结果
- CreateCompatibleDC的结果只有两种颜色