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?