Search code examples
javascriptbit-manipulationxor

Javascript xor ^ with 0 return bad result


I'm using the binary xor operator ^ with 2 variables like this :

var v1 = 0;
var v2 = 3834034524;
var result = v1 ^ v2;

The result is -460932772. Have you an idea why ?

Thank you


Solution

  • 3834034524, as a 32bit unsigned integer is hex E486B95C or binary 11100100100001101011100101011100. Notice that the most significant (leftmost) bit is set. This is the sign bit on 32bit signed integers.

    There, that bit pattern translates to decimal -460932772. The XOR operation is forcing the result into signed integers.

    Additional info: a 32bit signed integer can handle values from -2147483648 to +2147483647 (which your original value exceeded and it thus wrapped around). 32bit unsigned integers handle values from 0 to +4294967295. JavaScript is a dynamically typed language and the values may change types as needed. The number may become a floating point value, or bitwise operations may turn it into an integer, or it could become a string. There are some ways to use specific datatypes in recent versions of JavaScript, but this is not something you'd do with simple calculations.