programmar programmar - 1 year ago 118
Python Question

How to interpret 4 bytes as a 32-bit float using Python

I am sort of a novice to the Python language and am having a hard time doing something I could very easily do with C++ or Java but for some reason seems so convoluted to do in Python. I have the following four bytes in an array (in big endian order):

[0x64, 0xD8, 0x6E, 0x3F]

I already know beforehand what these bytes represent. They specify the following 32-bit floating-point number:

What are the steps I need to perform using Python (preferably v3.2.1 and without using extra imports) to interpret those 4 bytes as that float and store that number in a variable which I can manipulate as a 32-bit floating-point value? I.e. so i can use it just as the following variable
myVar = 0.932989

I've tried:

x = [0x64, 0xd8, 0x6e, 0x3f]
y = int.from_bytes(x, byteorder='little', signed=False) #interpret bytes as an unsigned little-endian integer (so far so good)
z = float(y) #attempt to cast as float reinterprets integer value rather than its byte values

has the right expected integer interpretation of those bytes, which is
, the problem comes when casting that to a 32-bit
. Instead of casting the raw bytes of
as a float, it casts the integer representation of those bytes, so
instead of the desired value of
. Is there maybe something equivalent to
that I can use to perform this simple task? Perhaps something like

Answer Source

For detail see Python Struct. For your specific question:

import struct

# if input is string, per @robyschek will fail on python 3
print struct.unpack('<f', data)   #little endian
print struct.unpack('>f', data)   # big endian

#your input  
list1=[0x64, 0xD8, 0x6E, 0x3F]
# aa=str(bytearray(list1))  # edit: this conversion wasn't needed
aa= bytearray(list1) 
print struct.unpack('<f', aa)