I'd like a simple way to convert a float string on the command line to a binary float.

For example:

$ echo "1.23" > file.bin

Except with the output as a 4 byte IEEE float

I'd expect the result of

$ od -f -An file.bin

2 Answers

John1024 On

I hope that there is a more compact way of doing this but, if not, try:

Python 2:

$ python -c "import sys,struct; sys.stdout.write(struct.pack('f', float(sys.argv[-1])))" 1.23 >file.bin
$ od -f -An file.bin

Python 3:

$ python3 -c "import sys,struct; sys.stdout.buffer.write(struct.pack('f', float(sys.argv[-1])))" 1.23 >file3.bin
$ od -f -An file3.bin

(Hat tip: Mark Dickinson)

How it works

  • import sys,struct

    Tells python to import the sys and struct modules.

  • sys.stdout.write(struct.pack('f', float(sys.argv[-1])))

    Tells python to take the last argument on the command line, sys.argv[-1]) and, use float to convert it to a float number, and use struct.pack to convert the float to a bit string, and finally use sys.stdout.write to send the bytes to stdout.

Shawn On

Similar, but less verbose, approach using Perl:

$ perl -e 'print pack("f", $ARGV[0])' 1.23 > file.bin