2014-09-27 61 views
2

我處於位移的可怕世界。我有以下代碼:C++中的右移給出了不尋常的結果(無符號64位)

我移這個號碼:140638023551944 >> 5.

爲140638023551944二進制表示根據http://www.binaryhexconverter.com/decimal-to-binary-converter

右移5,I預計有: 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"; 

「地址」填入正確的整數,140638023551944.我已經驗證了。

這是什麼奇怪的行爲?它與這個模擬器一致:http://www.miniwebtool.com/bitwise-calculator/bit-shift/?data_type=10&number=140638023551944&place=5&operator=Shift+Right!但我非常確定右轉不應該這樣工作!

+2

什麼類型是「地址」? – 2014-09-27 23:41:55

+0

@MatsPetersson它也是uint64_t。 – PinkElephantsOnParade 2014-09-27 23:42:47

+3

您的小數點轉換爲二進制轉換不正確。 28位二進制數當然不足以保存與15位十進制數相同的值。 – 2014-09-27 23:43:40

回答

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); 
    } 
} 
+0

OP中的代碼工作得很好。標記爲將問題關閉爲打印錯誤/不再可重現:請參閱OP上的註釋。 – OJFord 2015-01-03 19:43:03

相關問題