I have a javascript program there use bitwise OR operator to get a OR result from two numbers:
Sample code:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to return the number of characters in the string "Hello World!".</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "80400001";
var a = parseInt(str, 16);
var str = "12345678";
var b = parseInt(str, 16);
n = b|a;
document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>
But the result is always negative, that is not my expected value. Result:
-1837869447
Eventhough I try to OR a number with zero, the result is still negative...
It doesn't happen in Java, but in Javascript.
Can you tell how can I get the same result as that in Java?
You can use this change signed int to unsigned int:
n>>>0
var str = "80400001";
var a = parseInt(str, 16);
var str = "12345678";
var b = parseInt(str, 16);
n = b | a;
console.log((n>>>0).toString(16))
see: Bitwise operations on 32-bit unsigned ints?
I believe the problem is that unlike e.g. Java and Python JavaScript does not have a 64 bit integer type. When you use the bitwise operators in JS, the number is truncated to 32 bits, the operation is performed, then it is cast back to an IEEE 754 float. 0x80400001 is 2,151,677,953 which is bigger than 2,147,483,647 (max signed 32 bit int) and you're losing the significant bits which is giving the odd result.
There are arbitrary size integer libraries one can use.
Also checkout cyrilluce's answer for a way to do it without an external lib.
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