Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Half-Precision (2 byte) cast to Float in Python

Tags:

python

casting

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.

like image 760
Cenoc Avatar asked Sep 01 '25 04:09

Cenoc


2 Answers

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.

like image 65
ecatmur Avatar answered Sep 02 '25 18:09

ecatmur


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.

like image 25
Martijn Pieters Avatar answered Sep 02 '25 18:09

Martijn Pieters