C++中64位整数的Bitwise(Bitshift)操作

Shr*_*yas 5 c++ bit-manipulation bit-shift bitwise-or bitboard

我正在尝试处理位板,这需要我在64位无符号整数中设置一个特定的位.要设置位i,我对所讨论的位板执行按位OR运算,左移数字.

#include <stdint.h>
uint64_t kings = 0ULL; // Also tried unsigned long long int before.
kings |= 1 << i;
Run Code Online (Sandbox Code Playgroud)

它从第0位到第31位工作正常,但不能用于第32位到第63位.我怀疑这是因为右侧的评估恰好是32位整数.因此,我尝试了一个临时变量.

uint64_t temp = 0ULL;
temp |= 1 << i;
Run Code Online (Sandbox Code Playgroud)

也许它仍然将右侧评估为32位整数,或者它是我无法弄清楚的其他问题.要输出整数,我使用的是std :: bitset <64>.例如:

uint64_t kings = 0ULL;
kings |= 1 << 3;
kings |= 1 << 59;
Run Code Online (Sandbox Code Playgroud)

预期小数值:576460752303423496

实际:8

std::bitset<64> x(kings);
std::cout << x;
Run Code Online (Sandbox Code Playgroud)

位值:0000000000000000000000000000000000000000000000000000000000001000

显然,只有国王| = 1 << 3; 工作正常.

总之,第32到63位有什么问题,我该如何解决?

Arp*_*ius 12

1LL在使用shift operator <<获得64位结果之前,需要使用64位值:

#include <stdint.h>
uint64_t kings = 0ULL; 
kings |= 1ULL << i;
Run Code Online (Sandbox Code Playgroud)


The*_*ant 5

第32至63位有什么问题?

文字1是type int。移位运算符结果的类型是其LHS的类型(在对其执行常规算术转换之后)。在您的实现中,它似乎是32位,因此将其移位31位以上会产生不确定的行为。

使用64位整数作为移位运算符的左操作数:

temp |= static_cast<uint64_t>(1) << i;
Run Code Online (Sandbox Code Playgroud)