Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitshift in javascript

Tags:

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.

like image 579
Andrew Avatar asked Mar 03 '10 18:03

Andrew


People also ask

What is Bitshift used for?

A bit shift is a bitwise operation where the order of several bits is moved, either to the left or right, to efficiently perform a mathematical operation. Bit shifts help with optimization in low-level programming because they require fewer calculations for the CPU than conventional math.

What is XOR in JS?

The bitwise XOR operator ( ^ ) returns a 1 in each bit position for which the corresponding bits of either but not both operands are 1 s.

What is Javascript bitwise?

Bitwise operators treat its operands as a set of 32-bit binary digits (zeros and ones) and perform actions. However, the result is shown as a decimal value.

How does Bitshift work in Java?

The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator " >>> " shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.


1 Answers

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.)

like image 111
kennytm Avatar answered Sep 17 '22 17:09

kennytm