gpt4 book ai didi

javascript - JS 按位移位运算符 '>>' 未返回正确结果

转载 作者:行者123 更新时间:2023-12-01 15:52:40 24 4
gpt4 key购买 nike

我在 JS 中发现了这个奇怪的问题。我有一些与棋盘游戏 api 的 native 绑定(bind),它使用位板来表示游戏状态。
我正在尝试在 JS 中操作这些位板以在基于 Web 的 GUI 中显示结果(使用电子)。1位板上的 s 代表棋子的位置。这是一个例子:

const bitboard = 0b100000010000000000000000000000000000;
然而,当我做 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 binary

编辑:
相同的代码适用于 Rust,这是我在 native 端使用的语言。

最佳答案

某处可能有重复的 float ,但这里的解决方案是使用 BigInt

BigInt is a built-in object that provides a way to represent whole numbers larger than 253 - 1, which is the largest number JavaScript can reliably represent with the Number primitive and represented by the Number.MAX_SAFE_INTEGER constant. BigInt can be used for arbitrarily large integers.


您只需要确保右移运算符的两个操作数是相同的类型。

const bitboard = BigInt("0b100000010000000000000000000000000000")
console.log(bitboard.toString(2))
console.log((bitboard >> 1n).toString(2)) // note "1n"

关于javascript - JS 按位移位运算符 '>>' 未返回正确结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63697853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com