0

I was recently doing a bit manipulation problem where I was required to left shift a large number. My initial idea was to simply use the left shift operator and write num << i where i is the number of bits I want to shift. Easy enough.

The difficulty came when I attempted to shift numbers that were quite large. In these instances my answer came out to be wrong. So I started looking at other peoples answer to this problem and saw many others using num * (2 ** i) instead of num << i.

I understand how these two accomplish the same thing on smaller inputs, but fail to understand why one seems to cause overflow with larger values of num whereas the other is fine. What is the reasoning here?

When num is small, they yield the same answer.

const i = 4;
const num = 1234;

num * (2 ** i)  // 19744
num << i        // 19744

When num is large the shift operator overflows.

const i = 4;
const num = 462911488;

num * (2 ** i)  // 7406583808
num << i        // -1183350784

And does this mean I am never better off always using << since it has overflow issues?

Espresso
  • 740
  • 13
  • 32
  • Potential duplicate of [Left shift results in negative numbers](https://stackoverflow.com/questions/54030623/left-shift-results-in-negative-numbers-in-javascript)? – kelsny Sep 23 '22 at 18:55
  • Well, not quite. I understand why left shifting a big number causes an overflow - we run out of our 32 bits. What I don't understand is why `num * (2 ** i)` doesn't overflow. – Espresso Sep 23 '22 at 19:16
  • Bitwise operators convert their operands to 32-bit integers, but JavaScript numbers are double-precision floating-point numbers and arithmetic operations such as multiplication and exponentiation don't convert their operands to 32-bit integers. – Luke Woodward Sep 23 '22 at 19:48
  • Realize this is a dated question, but one can make use of BigInt and not run into this limitation. Also, if 64 bits is sufficient, one can use BigUint64Array elements... – Trentium Dec 17 '22 at 22:59

0 Answers0