C++ 中 64 位整数的按位 (Bitshift) 运算
Bitwise (Bitshift) operations on 64-bit integers in C++
我正在尝试处理位板,这需要我在 64 位无符号整数中设置特定位。要设置位 i,我对有问题的位板执行按位或,左移数字。
#include <stdint.h>
uint64_t kings = 0ULL; // Also tried unsigned long long int before.
kings |= 1 << i;
它从第 0 位到第 31 位工作正常,但对第 32 到 63 位不起作用。我怀疑这是因为右侧的评估恰好是 32 位整数。因此,我尝试了一个临时变量。
uint64_t temp = 0ULL;
temp |= 1 << i;
也许它仍然将右侧计算为 32 位整数,或者这是我无法弄清楚的其他问题。为了输出整数,我使用 std::bitset<64>。例如:
uint64_t kings = 0ULL;
kings |= 1 << 3;
kings |= 1 << 59;
预期十进制值:576460752303423496
实际:8
std::bitset<64> x(kings);
std::cout << x;
位值:00000000000000000000000000000000000000000000000000000000000001000
显然,只有国王 |= 1 << 3;工作正常。
总而言之,第 32 位到第 63 位有什么问题,我该如何解决?
在使用 shift operator <<
获得 64 位结果之前,您需要使用 1LL
作为 64 位值:
#include <stdint.h>
uint64_t kings = 0ULL;
kings |= 1ULL << i;
您需要对 64 位整数进行位移:
kings |= 1i64 << 59;
what is the issue with bits 32 to 63?
文字 1 的类型为 int
。移位运算符结果的类型是其 LHS 的类型(在对其执行了通常的算术转换之后)。它在您的实现中似乎是 32 位,因此将其移动超过 31 位会产生未定义的行为。
使用64位整数作为移位运算符的左操作数:
temp |= static_cast<uint64_t>(1) << i;
我正在尝试处理位板,这需要我在 64 位无符号整数中设置特定位。要设置位 i,我对有问题的位板执行按位或,左移数字。
#include <stdint.h>
uint64_t kings = 0ULL; // Also tried unsigned long long int before.
kings |= 1 << i;
它从第 0 位到第 31 位工作正常,但对第 32 到 63 位不起作用。我怀疑这是因为右侧的评估恰好是 32 位整数。因此,我尝试了一个临时变量。
uint64_t temp = 0ULL;
temp |= 1 << i;
也许它仍然将右侧计算为 32 位整数,或者这是我无法弄清楚的其他问题。为了输出整数,我使用 std::bitset<64>。例如:
uint64_t kings = 0ULL;
kings |= 1 << 3;
kings |= 1 << 59;
预期十进制值:576460752303423496
实际:8
std::bitset<64> x(kings);
std::cout << x;
位值:00000000000000000000000000000000000000000000000000000000000001000
显然,只有国王 |= 1 << 3;工作正常。
总而言之,第 32 位到第 63 位有什么问题,我该如何解决?
在使用 shift operator <<
获得 64 位结果之前,您需要使用 1LL
作为 64 位值:
#include <stdint.h>
uint64_t kings = 0ULL;
kings |= 1ULL << i;
您需要对 64 位整数进行位移:
kings |= 1i64 << 59;
what is the issue with bits 32 to 63?
文字 1 的类型为 int
。移位运算符结果的类型是其 LHS 的类型(在对其执行了通常的算术转换之后)。它在您的实现中似乎是 32 位,因此将其移动超过 31 位会产生未定义的行为。
使用64位整数作为移位运算符的左操作数:
temp |= static_cast<uint64_t>(1) << i;