简体   繁体   English

javascript中的XOR运算符与python中的XOR运算符不同

[英]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. 我试图将一些javascript代码复制到python中,由于某种原因,javascript中的XOR运算符(^)给出了与python中的XOR运算符(^)不同的值。 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? 我知道由于Math.random(),值应该是不同的,但为什么它会像4位有效数字更长?

Javascript: 使用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. 给定XOR的输入位,您的Python结果是正确的。 Your longer operand is on the order of 2^40, and so is your final result. 您的较长操作数大约为2 ^ 40,您的最终结果也是如此。

The Javascript result has been truncated to 32 bits, the shorter operand. Javascript结果被截断为32位,即较短的操作数。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators : 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. 按位运算符将其操作数视为32位 (零和1)的序列,而不是十进制,十六进制或八进制数。 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. 例如,十进制数字9具有1001的二进制表示。按位运算符在这样的二进制表示上执行它们的操作,但它们返回标准JavaScript数值。

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: 但是,您正在使用的特定代码可以通过XOR来“修复”您的数字的32位部分,并简单地添加其余部分:

 // 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) (由于21474836480x8000000 ,随机部分是“精细”,它不会被截断)

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

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