简体   繁体   English

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

[英]Bitwise (Bitshift) operations on 64-bit integers in C++

I'm trying to deal with bitboards, which requires me to set a particular bit in a 64-bit unsigned integer. 我正在尝试处理位板,这需要我在64位无符号整数中设置一个特定的位。 To set bit i , I perform a bitwise OR with the bitboard in question, with a left shifted number. 要设置位i ,我对所讨论的位板执行按位OR运算,左移数字。

#include <stdint.h>
uint64_t kings = 0ULL; // Also tried unsigned long long int before.
kings |= 1 << i;

It works fine from bit 0 to bit 31, but fails to work for bits 32 to 63. I suspect it's because the evaluation of the right side happens to be in a 32-bit integer. 它从第0位到第31位工作正常,但不能用于第32位到第63位。我怀疑这是因为右侧的评估恰好是32位整数。 Therefore, I tried a temporary variable. 因此,我尝试了一个临时变量。

uint64_t temp = 0ULL;
temp |= 1 << i;

Perhaps it still evaluates the right hand side as a 32-bit integer, or that it's some other problem I cannot figure out. 也许它仍然将右侧评估为32位整数,或者它是我无法弄清楚的其他问题。 To output the integer, I'm using std::bitset<64>. 要输出整数,我使用的是std :: bitset <64>。 For example: 例如:

uint64_t kings = 0ULL;
kings |= 1 << 3;
kings |= 1 << 59;

Expected decimal value: 576460752303423496 预期小数值:576460752303423496

Actual: 8 实际:8

std::bitset<64> x(kings);
std::cout << x;

Bit value: 0000000000000000000000000000000000000000000000000000000000001000 位值:0000000000000000000000000000000000000000000000000000000000001000

Clearly, only kings |= 1 << 3; 显然,只有国王| = 1 << 3; worked correctly. 工作正常。

In summary, what is the issue with bits 32 to 63 and how can I work around it? 总之,第32到63位有什么问题,我该如何解决?

You need to use 1LL as 64 bit value before you use shift operator << to get 64 bit result: 在使用shift operator <<获得64位结果之前,需要使用1LL作为64位值:

#include <stdint.h>
uint64_t kings = 0ULL; 
kings |= 1ULL << i;

what is the issue with bits 32 to 63? 32到63位有什么问题?

The literal 1 is of type int . 文字1的类型为int The type of a shift operator's result is the type of its LHS (after usual arithmetic conversions have been performed on it). 移位运算符的结果类型是其LHS的类型(在对其执行通常的算术转换之后)。 It appears to be 32 bits on your implementation, so shifting it by more than 31 bits yields undefined behavior. 它的实现似乎是32位,因此将其移位超过31位会产生未定义的行为。

Use a 64-bit integer as the left operand of the shift operator: 使用64位整数作为移位运算符的左操作数:

temp |= static_cast<uint64_t>(1) << i;

你需要bithift一个64位整数:

kings |= 1i64 << 59;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM