I'm trying to read a binary file that consists of 2 byte floats, but I cant seem to get the values I want. struct.unpack seems to only work for 4 byte floats and I'm not sure what else is available other than doing the cast completely manually. Is there any way to do this? Any help would be very much appreciated.
You've already got most of the way with numpy.fromfile
. Instead use numpy.frombuffer
:
>>> np.frombuffer(buffer("\0\0"), dtype=np.float16)[0]
0.0
>>> np.frombuffer(buffer("\x00\x3c"), dtype=np.float16)[0]
1.0
If the data has a known form you can parse out structs by creating a dtype with the appropriate layout.
You could pad them out to 4-byte single-precision floats; there are a few people who already have done the gruntwork for you:
http://forums.devshed.com/python-programming-11/converting-half-precision-floating-point-numbers-from-hexidecimal-to-decimal-576842.html
http://davidejones.com/blog/1413-python-precision-floating-point/
http://fpmurphy.blogspot.no/2008/12/half-precision-floating-point-format_14.html
They all parse out the format into it's constituents as documented on the Wikipedia article on the format, padding out the 2 bytes to a 4 bytes single-precision float, then feed that back to the python struct module for converting that to a python float.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With