Bitshift in javascript

Andrew picture Andrew · Mar 3, 2010 · Viewed 15k times · Source

I've got a really big number: 5799218898. And want to shift it right to 13 bits.
So, windows-calculator or python gives me:

5799218898 >> 13 | 100010100100001110011111100001 >> 13
70791            | 10001010010000111

As expected.

But Javascript:

5799218898 >> 13 | 100010100100001110011111100001 >> 13
183624           | 101100110101001000

I think it because of internal integer representation in javascript, but cannot find anything about that.

Answer

kennytm picture kennytm · Mar 3, 2010

In ECMAScript (Javascript) bitwise operations are always in 32-bit. Therefore 5799218898 is chopped into 32-bit which becomes 1504251602. This integer >> 13 gives 183624.

In Python they are arbitrary-length integers. So there's no problem.

(And the numbers in Windows calculator are 64-bit, enough to fit 5799218898.)

(And the correct answer should be 707912.)