I need to convert a vector of float numbers to bytes. I can't seem to find a way to do that in emacs-lisp. Is it possible?
For example how do I convert this vector [3.14]
to bytes?
[Update] See this comment by @dalanicolai, especially for the function IEEE-float-2-hex
.
Then, see https://stackoverflow.com/questions/12003231/how-do-i-convert-a-string-of-hex-into-ascii-using-elisp for how to convert a hex string to chars.
With those two functions I can run this:
(cl-loop for char across (reverse (decode-hex-string (IEEE-float-2-hex 3.14)))
concat (byte-to-string char))
to get a byte string (the original question), or this to write it to a file.
(with-temp-file "bin3"
(cl-loop for char across (reverse (decode-hex-string (IEEE-float-2-hex 3.14)))
do (insert (byte-to-string char))))
WhichThe reverse
here seems related to big vs little endian. Otherwise, that seems to write a byte string to a file that represents 3.
And then this14. This python can read it correctly. I still don't know how to read it in to emacs-lisp, but that isn't something I need at the moment (I just would like to know).
#+BEGIN_SRC jupyter-python
import struct
with open('bin3', 'rb') as f:
print(struct.unpack('f', f.read()))
#+END_SRC
#+RESULTS:
:RESULTS:
(3.1399998664855957,)
:END:
The small difference from 3.14 is from not being able to exactly represent a float number in 32 bits.