简体   繁体   中英

XOR output is wrong in Javascript

I am performing following operation

 let a = 596873718249029632; a ^= 454825669; console.log(a);

Output is 454825669 but the output should have been 596873718703855301 . Where I am doing wrong? What I should do to get 596873718703855301 as output?

EDIT: I am using nodejs Bigint library, my node version is 8.12.0

var bigInt = require("big-integer");

let xor = bigInt(596873718249029632).xor(454825669);
console.log(xor)

Output is

{ [Number: 596873717794203900]
  value: [ 4203941, 7371779, 5968 ],
  sign: false,
  isSmall: false } 

It is wrong. it should have been 596873718703855301 .

From MDN documentation about XOR :

The operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). Numbers with more than 32 bits get their most significant bits discarded.

Since the 32 least significant bits of 596873718249029632 are all 0, then the value of a is effectively 0 ^ 454825669 , which is 454825669 .

To get the intended value of 596873718703855301 , BigInts can be used, which allow you to perform operations outside of the range of the Number primitive, so now your code would become:

 let a = 596873718249029632n; a ^= 454825669n; console.log(a.toString());


In response to your edit, when working with integers and Number , you need to ensure that your values do not exceed Number.MAX_SAFE_INTEGER (equal to 2 53 - 1, beyond that point the double precision floating point numbers loose sufficient precision to represent integers). The following snippet worked for me:

var big_int = require("big-integer");
let xor = bigInt("596873718249029632").xor("454825669");
console.log(xor.toString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM