如何处理javascript中的256位数字并对其进行位运算?

How to deal with 256 bit numbers in javascript and perfom bitwise operations on them?

如何处理javascript中的256位数字并对其进行双向运算?

来自here 我已经阅读

JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers.

Before a bitwise operation is performed, JavaScript converts numbers to 32 bits signed integers.

After the bitwise operation is performed, the result is converted back to 64 bits JavaScript numbers.

我正在使用 solidity,所以如果我可以在 javascript 中操作 256 位数字就太好了。我怎样才能做到这一点?

解决此问题的最简单方法是使用 BigInts,它是任意大的整数。可以进行位运算,但是两个操作数必须是BigInts,例如:

const x = (12n ** 122n) & (13n ** 133n);

x; // 456858437811811283460933542382254067662103063706637216731032202770157889962434550961221416858884249781343525362849766767350670950400n

另一种方法是直接使用数字的字节并对每个字节独立应用按位运算,但这种方法更复杂,您不能用简单的数字原语表示这些数字。但是如果你的平台 运行 代码不支持 BigInt 原语,这是唯一的方法。