1

How to deal with 256 bit numbers in javascript and perform bitwise 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?

1 Answer 1

3

By using the ethers.js library:

const { BigNumber } = require('ethers')
const a = BigNumber.from(1).shl(255) // 1 << 255 = 0x80...00
const b = BigNumber.from(1)          //            0x00...01
const c = a.or(b)                    //            0x80...01

Not the answer you're looking for? Browse other questions tagged or ask your own question.