Reputation: 7706
How to deal with 256 bit numbers in javascript and perfom biwise operations on them?
From here I have read that
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.
I am working with solidity and so it would be great if I could manipulate 256 bit numbers in javascript. How can I achieve this?
Upvotes: 1
Views: 740
Reputation: 11245
The easiest way for this problem will to use BigInts, which are arbitrarily large integers. You can do bitwise operations, but both operands must be BigInts, as an example:
const x = (12n ** 122n) & (13n ** 133n);
x; // 456858437811811283460933542382254067662103063706637216731032202770157889962434550961221416858884249781343525362849766767350670950400n
Another way would be to use the bytes of the number directly and apply the bitwise operations independently on each byte, but this way is more complex and you cannot represent these numbers with the simple number primitive. But if the platform you are running the code do not support BigInt
primitive this is the only way.
Upvotes: 2