Javascript – How to simulate a bitwise rotation of a 64-bit (unsigned) integer in JavaScript

bit-manipulationjavascript

I need to perform a circular left shift of a 64-bit integer in JavaScript. However:

  • JavaScript numbers are doubles
  • JavaScript converts them to 32-bit signed ints when you start with the << and the >> and the >>> and the ~ and all of the bit-twiddling business. And then it's back to doubles when you're done. I think.
  • I don't want the sign. And I definitely don't want the decimal bits. But I definitely do want 64 bits.

So, how do I perform a bitwise left rotation of a 64-bit value?

Best Answer

Keep your 64-bit number as separate high and low partitions. To rotate left N when N < 32:

hi_rot = ((hi << N) | (lo >>> (32-N))) & (0xFFFFFFFF)

lo_rot = ((lo << N) | (hi >>> (32-N))) & (0xFFFFFFFF)

If N >= 32, then subtract 32 from N, swap hi and lo, and then do the above.