Luk*_*eek 3 javascript bitwise-operators
我在 JS 中发现了这个奇怪的问题。我有一些与棋盘游戏 api 的本机绑定,它使用位板来表示游戏状态。我试图在 JS 中操作这些位板以在基于 Web 的 GUI(使用电子)中显示结果。
1bitboard 中的s 代表棋子的位置。下面是一个例子:
const bitboard = 0b100000010000000000000000000000000000;
Run Code Online (Sandbox Code Playgroud)
但是,当我这样做时bitboard >>= 1;,值神奇地变成了0b1000000000000000000000000000。
可运行示例:
const bitboard = 0b100000010000000000000000000000000000; // 0b is binary literal
console.log(bitboard.toString(2));
console.log((bitboard >> 1).toString(2)); // .toString(2) prints the number in binaryRun Code Online (Sandbox Code Playgroud)
编辑:相同的代码适用于 Rust,这是我在本机端使用的语言。
某处可能有一个重复的漂浮物,但这里的解决方案是使用 BigInt
BigInt是一个内置对象,它提供了一种表示大于 2 53 - 1 的整数的方法,这是 JavaScript 可以用Number原语可靠表示并由Number.MAX_SAFE_INTEGER常量表示的最大数字。BigInt可用于任意大的整数。
您只需要确保右移运算符的两个操作数是相同的类型。
const bitboard = BigInt("0b100000010000000000000000000000000000")
console.log(bitboard.toString(2))
console.log((bitboard >> 1n).toString(2)) // note "1n"Run Code Online (Sandbox Code Playgroud)