Bit Shift vs Multiplication

I am trying to convert an array of bytes to a number and for large numbers, I see that a bit shift gives -ve results. Can any of you please why we see this problem? Do you see any flaws using "multiplication" instead of "bit shift"?

For instance,

<script language="JavaScript"> var myVar = 1000000; document.write("Bit shift Result: " + (myVar << 8)); document.write("<br>"); document.write("Multiplication Result: " + parseInt(myVar *256)); </script> 

Output:

Bit Shift Result: 256000000

Multiplication Result: 256000000

After adding another zero to myVar, you see the problem I'm talking about

 <script language="JavaScript"> var myVar = 10000000; document.write("Bit shift Result: " + (myVar << 8)); document.write("<br>"); document.write("Multiplication Result: " + parseInt(myVar *256)); </script> 

Output:
Bit Shift Result: -1734967296

Multiplication Result: 2560000000

+6
source share
3 answers

To answer both questions:

Can any of you understand why we are seeing this problem?

JavaScript numbers are standard IEEE doublings.

The largest integer value that JavaScript may contain is: 9007199254740992

However, the bit-shift operator works on 32-bit ints.

And I quote the language specification :

5. Let lnum be ToInt32 (lval).

...

Returns the result of performing a right shift of the lnum shift sign with the shiftCount bits. The most significant bit multiplies. The result is a signed 32-bit integer.

Do you see any flaws using "multiplication" instead of "bit-shift"?

It still looks slower, but you should really avoid working with very large numbers in JavaScript anyway.

There are libraries that handle very large numbers, and there are functions that are discussed to add better support to large numbers in the language (ES7 value types).

+2
source

In JavaScript, all bitwise operators first call [ToInt32] on the operands. This includes shift operators.

Then, bitwise operators (i.e., << ) work on signed two-part 32-bit integers. After the shift, the resulting bit chart is a negative number.

 00000000 10011000 10010110 10000000 - original value, after [ToInt32], as bits 10011000 10010110 10000000 00000000 - value after shift; a negative bit pattern 

I would use multiplication, unless this behavior is desired.

(Of course, if you write a PC emulator , then every little trick counts ... but prefers multiplication.)

+3
source

JavaScript internally represents all numbers using a 64-bit float with a 52-bit mantissa. However, you can also perform bit operations, but only as signed 32-bit integers that go from -2147483648 to +2147483647. To go beyond this range, you should use regular arithmetic rather than bitwise operations.

+1
source

All Articles