Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bit shift vs multiplication

I am trying convert a byte array to a number and for large numbers, I see that the bit shift is giving -ve results. Can one of you please why we see this issue? Do you see any drawbacks using "multiplication" instead of "bit-shift"?

For example,

<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

Upon adding one more zero to myVar, you see the issue I am 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

like image 863
user3101143 Avatar asked Dec 13 '13 23:12

user3101143


1 Answers

To answer both your questions:

Can one of you please why we see this issue?

JavaScript numbers are standard IEEE doubles.

The largest integer value JavaScript can hold is: 9007199254740992

However, the bitshift operator works on 32 bit ints.

And I quote the language specification:

5 . Let lnum be ToInt32(lval).

...

Return the result of performing a sign-extending right shift of lnum by shiftCount bits. The most significant bit is propagated. The result is a signed 32-bit integer.

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

It still is kind of slower, but you should really avoid working directly with very large numbers in JavaScript most of the time anyway.

There are libraries that deal with very large numbers and there are features that are being discuss to add better support to large numbers to the language (ES7 value types).

like image 144
Benjamin Gruenbaum Avatar answered Oct 13 '22 13:10

Benjamin Gruenbaum