1

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
2
  • Python has arbitrary precision, but JavaScript not so much. See JavaScript's BigInt module for guidance. Commented Jun 11, 2019 at 16:16
  • Javascript converts the inputs (and therefore output) to an Int32. Commented Jun 11, 2019 at 16:24

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)

2 Comments

Small question, I want to do what you just did but in reverse. I want to use the code which javascript does, in python. I still have no clue how to convert a normal number to a 32 bit number, nor do I know what a 32 bit number is exactly. Thank you for your brief explanation though, it gave me some insight on what to research.
@CarlosIsLazy if you want to "cut back" a number to 32 bits, you can use a bitwise and operation, with 32 bits: somenumber & 0xFFFFFFFF (one hexadecimal F is 1111 in binary, so 8 of them are 8*4=32 bits)

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.