简体   繁体   English

XOR output 在 Javascript 中是错误的

[英]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 . Output 是454825669但 output 应该是596873718703855301 Where I am doing wrong?我在哪里做错了? What I should do to get 596873718703855301 as output?我应该怎么做才能得到596873718703855301作为 output?

EDIT: I am using nodejs Bigint library, my node version is 8.12.0编辑:我正在使用 nodejs Bigint 库,我的节点版本是 8.12.0

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

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

Output is Output 是

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

It is wrong.这是错误的。 it should have been 596873718703855301 .它应该是596873718703855301

From MDN documentation about XOR :来自关于 XOR 的 MDN 文档

The operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones).操作数转换为 32 位整数并由一系列位(零和一)表示。 Numbers with more than 32 bits get their most significant bits discarded.超过 32 位的数字将被丢弃其最高有效位。

Since the 32 least significant bits of 596873718249029632 are all 0, then the value of a is effectively 0 ^ 454825669 , which is 454825669 .由于596873718249029632的 32 个最低有效位均为 0,因此a的值实际上是0 ^ 454825669 ,即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:要获得596873718703855301 的预期值,可以使用 BigInts 596873718703855301它允许您执行Number原语范围之外的操作,因此现在您的代码将变为:

 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).为了响应您的编辑,在使用整数和Number时,您需要确保您的值不超过Number.MAX_SAFE_INTEGER (等于 2 53 - 1,超过该点,双精度浮点数会失去足够的精度来表示整数) . The following snippet worked for me:以下片段对我有用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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