9

As I understand it, JS treats numbers as 32-bits when performing bit-shift operations, even though it supports 64-bit numbers.

How can I implement a leftShift function that works on 64-bit numbers? i.e., it won't roll over into the negatives for something like 192 << 24 (should be 3221225472, not -1073741824).

mpen
  • 272,448
  • 266
  • 850
  • 1,236

1 Answers1

12

Just do what the math of a left shift does:

Arithmetic shifts are equivalent to multiplication by a positive (to the left) or by a negative number (to the right), integral power of the radix (e.g. a multiplication by a power of 2 for binary numbers).

function shift(number, shift) {
    return number * Math.pow(2, shift);
}

shift(192, 24)
//3221225472

shift(3221225472, -24)
//192
David Gatti
  • 3,576
  • 3
  • 33
  • 64
dave
  • 62,300
  • 5
  • 72
  • 93
  • Thank you. I thought it was that simple, but I wasn't sure if I missing something. – mpen Oct 15 '15 at 00:00
  • You should add a Math.floor() because of rounding errors. For example `0xFFFFFFFF * Math.pow(2, -24) = 255.99999994039536` instead of 255. – Motla Feb 15 '22 at 16:19