简体   繁体   中英

XOR operator in javascript different from XOR operator in python

I am trying to replicate some javascript code into python, and for some reason the XOR operator (^) in javascript gives me a different value than the XOR operator (^) in python. I have an example below. I know the values should be different because of Math.random(), but why is it like 4 significant digits longer?

Javascript:

    console.log(Math.floor(2147483648 * Math.random()) ^ 1560268851466)
    = 1596700165

Python:

    import math
    math.floor(2147483648 * random.random()) ^ 1560268851466
    = 1559124407072

Your Python result is correct, given XOR's input bits. Your longer operand is on the order of 2^40, and so is your final result.

The Javascript result has been truncated to 32 bits, the shorter operand.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators :

Bitwise operators treat their operands as a sequence of 32 bits (zeroes and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

However the particular code you are using can be "fixed" via XOR -ing the 32-bit part of your number, and simply adding the rest:

 // 1560268851466 = 0x16B_4745490A console.log( (Math.floor(2147483648 * Math.random()) ^ 0x4745490A) + 0x16B00000000); 

(As 2147483648 is 0x8000000 , the random part is "fine", it does not get truncated)

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