Search code examples
javascriptbitwise-operators

What's the most efficient way to execute a bitwise operation on two long hex values in JS?


I'm trying to execute an AND operation on two 128-byte hexadecimal values. Something like:

let toReturn = (parseInt(bytesA, 16) & parseInt(bytesB, 16)).toString(16);

seems to work well for values not longer than 0xfffffff. Anything more than that, and I'm starting to get incorrect values.

I've considered iterating through both values - byte after byte, but my overall code is getting a little heavy, and various 128-byte values would need to be compared 8 times in a loop, that's nested in another loop (up to 50 iterations), all that on page load.

I'm hoping to find a more efficient solution for that.


Solution

  • Use BigInt:

    let toReturn = (BigInt('0x' + bytesA) & BigInt('0x' + bytesB)).toString(16);