python lightweight solution for typecasting float(64) to bytes

1.9k views Asked by At

I'd like to have a very simple solution in displaying the raw bytes for a float value (or more consecutive ones in memory). in my understanding, this is named typecasting (reading the memory values in byte) not to be misunderstood as casting (reading the value and interpreting that in byte).

The simplest test seem to be:

import numpy
a=3.14159265
print(a.hex())
# Returns 0x1.921fb53c8d4f1p+1
b=numpy.array(a)
print(b.tobytes())
# returns b'\xf1\xd4\xc8S\xfb!\t@'
# expected is something like 'F1' 'D4' 'C8' '53' 'FB' '21' '09' '40'

but the method hex() returns an Interpretation of the IEEE FLOAT represantation in hex. The second method shows four hex-Byte markers \x but I wonder as a float64 should read 8 Bytes. Further I'm wondering by the other characters.
I good old simple C I would have implemented that by simply using an unsigned int pointer on the memory address of the float and printing 8 values from that unsigned int "Array" (pointer.)
I know, that I can use C within python - but are there other simple solutions?
Maybe as it is of interest: I need that functionalaty to save many big float vectors to a BLOB into a database.

I think, similiar Problems are to be found in Correct interpretation of hex byte, convert it to float reading that if possible (displayable characters) they are not printed in \x-form. How can I change that?

1

There are 1 answers

0
John Zwinck On BEST ANSWER

You can use the built-in module struct for this. If you have Python 3.5 or later:

import struct
struct.pack('d', a).hex()

It gives:

'f1d4c853fb210940'

If you have Python older than 3.5:

import binascii
binascii.hexlify(struct.pack('d', a))

Or:

hex(struct.unpack('>Q', struct.pack('d', a))[0])

If you have an array of floats and want to use NumPy:

import numpy as np
np.set_printoptions(formatter={'int':hex})
np.array([a]).view('u8')