C++中的右移产生异常结果(无符号64位)
Right Shift in C++ giving unusual results (unsigned 64-bit)
我身处比特移位的可怕世界。我有以下代码:
我正在拨这个号码:140638023551944>>5。
140638023551944的二进制表示根据http://www.binaryhexconverter.com/decimal-to-binary-converter是
100001100011111011101000111
右移5,我预计:000001000011000111110111010
但是,我得到了4394938235998,即1111111111 01000110101110110111110001011110。
在我看来,这个数字与原来的数字几乎没有任何关系。我看不出一种模式存在于另一种模式中。这很奇怪。
代码大致如下:
uint64_t n, index, tag;
uint64_t one = 1;
uint64_t address = 140638023551944;
/*left shift to get index into the last index.length() number of slots*/
cout << "original address is " << address << " " << "n";
n = (address >> 5);
cout << "after right shifting away offset bits " << n << "n";
"地址"填充了正确的整数140638023551944。我已经证实了这一点。
这种奇怪的行为是什么?它与该模拟器一致:http://www.miniwebtool.com/bitwise-calculator/bit-shift/?data_type=10&号码=140638023551944&位置=5&operator=Shift+Right!但我敢肯定,正确的转变不应该是这样的!
// EVERYTHING WORKS CORRECTLY!
#include <cassert> // assert()
#include <iostream> // cout
#include <cstdint> // UINT64_MAX
using namespace std;
int main() {
uint64_t n, index, tag;
uint64_t one = 1;
uint64_t address = 140638023551944;
/*left shift to get index into the last index.length() number of slots*/
cout << "original address is " << address << " " << "n";
n = (address >> 5);
cout << "after right shifting away offset bits " << n << "n";
{ // Everything works correctly!
assert( 140638023551944>>5 == 140638023551944/32 );
assert( 140638023551944>>5 == 4394938235998 );
assert( 140638023551944/32 == 4394938235998 );
assert( 140638023551944 < UINT64_MAX );
}
}
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将无符号char*转换为std::istream*C++
- 是否可以将无符号 int 的最大值转换为 int 并将结果转换为 -1?
- 为什么 Clang 和 GCC 中两个无符号整数之和的结果类型不同
- C++,概念不适用于无符号整数作为结果类型?
- 将零附加到数字时,无符号数字会显示不同的结果
- 用有符号长整型结果减去无符号长整型
- 如何正确地将无符号字符转换为CString,并再次将CString的结果反向转换为无符号字符
- 错误 C4146:一元减号运算符应用于无符号类型,结果仍然无符号
- 将2^31赋给有符号和无符号的32位整数变量后的奇怪结果
- 无符号值之间的减法-意外结果
- 溢出的有符号/无符号赋值及其结果
- C++中的右移产生异常结果(无符号64位)
- 为什么无符号字符的结果<<无符号字符不是无符号字符
- 对于无符号字符,boost::lexical_cast 和 std::to_string 的正确结果是什么
- 减去无符号整数的有符号结果
- 显示无符号字符*和有符号字符*输出的结果是否完全相同
- 有符号/无符号比较会产生意想不到的结果
- 从double转换为无符号int时得到错误结果
- 有可能的方法可以将两个从无符号 int 铸造的浮点数除以产生负浮点数结果