javascriptbit-manipulationbitwise-operators

How can I force bitwise operators to produce unsigned results?


I'm working on a CRC32 algorithm in JavaScript, which I'm new to. Everything seems to go well until the last step: XOR the checksum with 0xFFFFFFFF.

1001010100111101101100010001000
 ^ 11111111111111111111111111111111 = -1001010100111101101100010001001

1251924104 ^ 4294967295 = -1251924105

It seems like the negative value is a problem. What can I do to address it?


Solution

  • A bitwise operation in Javascript will coerce a Number into a signed 32-bit integer, with a maximum value of 2^31-1. Your number, 0xFFFFFFFF, is 2^32-1.

    However, it will work fine if you use BigInts instead:

    console.log(0xFFFFFFFF ^ 0)
    
    console.log(String(0xFFFFFFFFn ^ 0n))

    Note: I had to use String() because the stackoverflow console.log function does not appear to handle BigInts.