移位时是否有 n 位的限制?

Is there a limit of n bits when bit shifting?

本文关键字:是否      更新时间:2023-10-16

在尝试为位板类提出方案时,我决定使用全局编译时变量来表示关键位板配置,例如所有黑鸦的初始位置。

constexpr uint64_t BLACK_ROOK_INIT  = 0x1 | (0x1 << 56);

但是我收到编译器错误。 编译器似乎将此值视为 32 位值,类型转换或添加额外的 0 似乎没有区别。 类型定义来自 。

一旦我从这个表达式中删除 constexp,它就会编译,但仍然会产生等效的警告。为什么会这样?我认为这可能是预处理器的限制,但是在没有constexp的情况下,问题仍然存在。

chess.cpp:16:64: error: right operand of shift expression ‘(1 << 56)’ is >= than the precision of the left operand [-fpermissive]

仅供参考,这也不会编译

constexpr int64_t BLACK_ROOK_INIT = (int64_t)0x1 | (int64_t)(0x1 << 32);

这是你想要的:

#include <iostream>
int main(){
constexpr uint64_t BLACK_ROOK_INIT  = 0x1ULL | (0x1ULL << 56);
std::cout<<BLACK_ROOK_INIT<<std::endl;
}

默认情况下,您的0x1值是一个int,通常实现为 32 位整数。

此处讨论后缀。如果他们让你有点不舒服,就像他们让我一样,你可以这样投射:

#include <iostream>
int main(){
constexpr uint64_t BLACK_ROOK_INIT  = (uint64_t)(0x1) | ((uint64_t)(0x1) << 56);
std::cout<<BLACK_ROOK_INIT<<std::endl;
}

这里的 1 是 int,移动后它超过了 int 的极限。 所以首先我们需要将 int 转换为长 long int(根据您的要求进行 A/C(

#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;                
ll l=(long long int)1<<n;
cout<<l<<endl;
}