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: -1734967296Multiplication Result: 2560000000
To answer both your questions:
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With