0

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.

3
  • Your first number is too large, you can use big-ints instead though: 596873718249029632n ^ 454825669n Commented Jul 14, 2020 at 6:28
  • when I use above syntax in nodejs , it is throwing "SyntaxError: Invalid or unexpected token" error Commented Jul 14, 2020 at 6:36
  • BigInts are new, so if you're using Safari, IE or an outdated browser then you'll face issues: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 14, 2020 at 6:41

1 Answer 1

4

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 253 - 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());
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you . it worked. I forgot toString() command
Glad I could help, if you found my answer useful please consider accepting it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.