1

I am writing a Python program which interacts with a webapp which I did not write. There is some state that I need to represent in my program which is not sent to the (javascript) client by the server, but is instead computed separately on both the client and the server with shared information.

For example, the exchange might go something like:

var x = getValueFromServer(); //client gets 0.73346
x *= 1 << 30;
result = x & 1023

My Python code successfully receives 0.73346, but I need the value of result. The result of the multiplication by 2^30 seems to be the same in javascript and Python, but I cannot directly mask the float value inside Python.

I have tried (for the above example value)

from struct import pack, unpack
unpack('q', pack('d', 0.73346))[0] & 1023

but this gives a value of 696 in Python, while when I run the above javascript in node I get a value of 566. I've also tried a few other combinations of packing and unpacking formats, with no success.

My last resort would be executing javascript from inside Python with a node subprocess, but I'd prefer to avoid that. How can I solve this?

6
  • How is python receiving the data to be used? Commented May 20, 2017 at 10:00
  • A websocket. That isn't particularly relevant here though. Technically it's not receiving a float directly, it receives some integers and computes the float, so there's no issue with decoding the float that is being used. Commented May 20, 2017 at 10:03
  • 1
    I'm not sure what you want to achieve with struct: that would be reinterpreting the bit pattern of the float as an integer, rather than doing something resembling an arithmetic operation. Does something like int(0.73346 * (1 << 30)) & 1023 do what you want? Commented May 20, 2017 at 10:28
  • Right so the expression you provided does not work in python, as bitwise operations aren't defined for floats. The unpack operation was an attempt to keep the bit order the same and allow that operation. Commented May 20, 2017 at 10:31
  • 1
    Did you try it? It works for me at the command line (in both Python 2 and Python 3). Commented May 20, 2017 at 10:35

1 Answer 1

3
x = 0.73346
x = x * (1 << 30)
x = int(x) & 1023

gives 566 in python

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

1 Comment

Ah it appears that the way javascript lets you use bitwise operations on floats is by casting them to ints... I didn't even consider that. Thanks!

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.