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
3 Answers
Reset to default 6This 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
版权声明:本文标题:bit manipulation - Javascript xor ^ with 0 return bad result - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744851994a2628548.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论