This is a variant of:
How to print float value from binary file in shell?
in that question, we wanted to print IEEE 754 single-precision (i.e. 32-bit) floating-point values from a binary file.
Now suppose that I want to print half-precision (i.e. 16-bit) floats. od doesn't seem to like doing this:
$ od -t f2 c.bin
od: invalid type string ‘f2’;
this system doesn't provide a 2-byte floating point type
and neither does perl's pack...
Bonus points if your answer also covers binary files with bfloat16 (also 16-bit) values.
The following is code generated by SO's "Ask with AI" for IEEE 754 half precision (I asked 2 different questions, merged the codes, and added a missing import):
Tests under bash or zsh (for the
printf\xsupport), with the 2 bytes ordered for a little-endian machine:This can be checked on the examples given at Half-precision floating-point format on Wikipedia.
Here's also a version for Perl, but only for normal numbers. The code was also generated by SO's "Ask with AI", but it was wrong (it mixed up 32-bit and 64-bit numbers), so I had to fix it (and also adapt the beginning for the question).
For bfloat16, this is even simpler as it can be viewed as the truncation of a binary32 binary string. So one just needs to shift the 2-byte integer by 16 bits to the left (i.e. insert 16 zeros on the right). Here's the code:
This can be checked on the examples at bfloat16 floating-point format on Wikipedia.