Skip to content Skip to sidebar Skip to footer

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 Pyth

Solution 1:

For detail see Python Struct. For your specific question:

import struct

# if input is string, per @robyschek will fail on python 3
data=b'\x64\xd8\x64\x3f'print struct.unpack('<f', data)   #little endianprint 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)
​

output:

(0.8939268589019775,)
(3.193376169798871e+22,)
(0.9329893589019775,)

Solution 2:

If you're willing to use a big library that's really for handling (large) arrays of numbers efficiently:

import numpy as np
data_bytes = np.array([0x64, 0xD8, 0x6E, 0x3F], dtype=np.uint8)
data_as_float = data_bytes.view(dtype=np.float32)
print(data_as_float)

This will also work on big byte arrays; then you get an array of floats.

Post a Comment for "How To Interpret 4 Bytes As A 32-bit Float Using Python"