admin管理员组

文章数量:1410737

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

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

Share Improve this question asked Nov 18, 2014 at 22:36 MieluneMielune 332 bronze badges 3
  • 1 How is that unexpected? – Bergi Commented Nov 18, 2014 at 22:37
  • 2 3834034524 > Math.pow(2,31) - 1 // true – zerkms Commented Nov 18, 2014 at 22:40
  • What is the point of doing that by the way? – zerkms Commented Nov 18, 2014 at 23:02
Add a ment  | 

3 Answers 3

Reset to default 6

This is an expected behavior these are signed numbers.

Just truncate the result to an unsigned integer

var result = (v1 ^ v2) >>> 0;

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 bee a floating point value, or bitwise operations may turn it into an integer, or it could bee 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.

The ToInt32 operation does not preserve the sign - it casts your number to a signed 32-bit representation. Since 3834034524 is larger than 231, it will overflow and result in a negative integer.

  010           --ToInt32-->  000000000000000000000000000000002
^ 383403452410  --ToInt32-->  111001001000011010111001010111002
                                         V xor V
= -46093277210  <-fromInt32-  111001001000011010111001010111002

本文标签: bit manipulationJavascript xorwith 0 return bad resultStack Overflow