1

Suppose I've set a bash variable to some fractional value (e.g. x=1.5). Now, I want to write the value of x to a file (e.g. my_file) - but not as text; rather, I want to write a 32-bit IEEE-754 floating point value.

Can I do this with bash and standard(ish) Unix command-line tools?

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • 2
    This may help... https://stackoverflow.com/a/36794412/2836621 – Mark Setchell Jul 25 '21 at 12:17
  • It's possible with bash builtin only too, as Bash has bitwise operators. It's only then math to build an IEEE-754 representation. However, it would be very slow. Are you looking for a bash only answer ? – Zilog80 Jul 25 '21 at 12:51
  • @Zilog80: Not necessarily; I did say "standard command-line tools". Also, a contrived answer would not be great. – einpoklum Jul 25 '21 at 13:03

1 Answers1

3

(Due to a hint from @MarkSetchell:)

Write:

perl -e "print pack('f>',${x})" > my_file

While perl not strictly a simple command-line utility, it is very popular to have installed; and the code is pretty terse.

einpoklum
  • 118,144
  • 57
  • 340
  • 684