Question

In python:

crc = -1 ^ int("0x806567CB",16)
print crc

results in: -2154129356.

In javascript:

<html>

<body onload="test()"></body>
<script>
function test()
{

crc = -1 ^ ("0x806567CB");    
document.write(crc);
}
</script>

</html>

results in: 2140837940.

Why the difference?

Was it helpful?

Solution

Python has arbitrary precision integers and therefore the number 0x806567CB is just a regular positive integer.

Javascript instead converts numbers to 32-bit integers when doing bitwise operations. What javascript is giving you is the same Python result but truncated to 32 bits.

To get the same result in Python:

 x = x & 0xFFFFFFFF   # Keep only 32 bits
 if x >= 0x80000000:
     # Consider it a signed value
     x = -(0x100000000 - x)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top