Do you ever want to bring a 64-bit floating point number created in Python to JavaScript as it is? Both are IEEE-754 64-bit (sign 1 bit, mantissa 52 bits, exponent 11 bits).
I wish I could pass it as it is, but I'm not happy that if I dump it and put it out in decimal, it will be rounded.
This entry details how to pass a floating point number as is, without error.
In reality, JavaScript is defined by the ECMAScript specification, and Python is the same as C double, so as a result, it has the same format in most existing OS environments.
float64 is a byte array using struct.pack and then a hexadecimal string in format. It is issued in network byte order.
dump.py
>>> import numpy as np
>>> import struct
>>> import binascii
>>> a = np.float64(10.12345456)
>>> binascii.hexlify(struct.pack("!d", a))
'40243f356fa37bf1'
Although it is a little different from this explanation, you can also restore it as follows.
load.py
>>> b = struct.unpack('!d', binascii.unhexlify('40243f356fa37bf1'))[0]
>>> a == b
True
Use the familiar TypedArray
> a = new ArrayBuffer(8)
> b = new Float64Array(a)
> c = new Uint32Array(a)
> d = '40243f356fa37bf1'
> c[0] = parseInt(d.slice(8, 16), 16)
> c[1] = parseInt(d.slice(0, 8), 16)
> b[0]
10.12345456
Yes. I was able to read it. I tried it with Python 3.4 on Mac OS X 10.9 and node.js 0.12.2.
Recommended Posts