C ++中的右移给出了不寻常的结果(无符号64位)

时间:2014-09-27 23:39:45

标签: c++ binary-operators

我处在一个可怕的位移世界。我有以下代码:

我正在转移这个号码:140638023551944>> 5.

根据http://www.binaryhexconverter.com/decimal-to-binary-converter的140638023551944的二进制表示是

1000011000011111011101000111

右移5,我期待:0000010000110000111110111010

但相反,我得到4394938235998,即111111111101000110101110110111110001011110。

对我而言,这个数字看起来与原始数字几乎没有任何关系。我没有看到另一个中存在的模式。这很奇怪。

代码如下:

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";

“address”填充了正确的整数140638023551944.我已经验证了这一点。

这种奇怪的行为是什么?它与此模拟器一致:http://www.miniwebtool.com/bitwise-calculator/bit-shift/?data_type=10&number=140638023551944&place=5&operator=Shift+Right!但我很确定正确的转变不应该那样工作!

1 个答案:

答案 0 :(得分:0)

// 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 );
    }
}