gpt4 book ai didi

c++ - C++ 中的右移给出异常结果(无符号 64 位)

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:52:27 26 4
gpt4 key购买 nike

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

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

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

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

“地址”填入了正确的整数 140638023551944。我已经验证过了。

这是什么奇怪的行为?和这个模拟器是一致的:http://www.miniwebtool.com/bitwise-calculator/bit-shift/?data_type=10&number=140638023551944&place=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++ - C++ 中的右移给出异常结果(无符号 64 位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26080194/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com