0

I noticed an odd behavior with Javascript: when I execute 1967779 << 11 I get a negative result: -264955904

However, if I run that same line in a Python interpreter, I get the correct answer: 4030011392

Note that both Firefox's and Chrome's Javascript consoles returned the same negative number, so it must be an issue with Javascript itself and not the engine.

Why am I getting different values between Python and Javascript? What can I do to work around this? How does the Javascript left shift operator work?

drdrez
  • 921
  • 1
  • 7
  • 16

1 Answers1

4

Because the return value of this bitwise operation in your JavaScript engine is a signed 32-bit integer that can only represent numbers from -2147483648 to 2147483647.

The control of whatever an integer is negative or positive is done by setting the signal bit, the bit of highest relevance in the 32-bits chain (2^31). If 0 its positive, if 1 its negative.

So it happens that 4030011392 is bigger than 2147483647 and it means the signal bit was "accidentally" set to 1 in the process, causing the number to become negative.

Havenard
  • 27,022
  • 5
  • 36
  • 62