How to print float value from binary file in shell?

点点圈 提交于 2019-12-04 08:28:17
Mark Setchell

This doesn't use Python and is a widely-used external tool, Perl.

perl -e "print pack('d>',0.123)" > file.bin

perl -e "print unpack('d>',<>)" < file.bin
0.123

Or you can use GNU od utility, e.g.:

od -tfD file.bin
0000000                    0.123
0000010

Where -t parameter specifies the output format for floating-point number (f) followed by optional size specifier (F for float, D for double or L for long double), in short -tfD can be replaced by -e or -F. To print only value without address, -A n can be specified.

od -f <filename>

That will dump your file as floats.

od is a standard Linux tool, and it's what I use. The manpage reads:

od - dump files in octal and other formats

As a oneliner

echo -n "000000000000f03f" | while read -N2 code; do printf "\x$code"; done | od -t f8
aphorise

You may wish to consider some of the mentioned tools such as bc which can be used in arithmetic operations and comparisons - eg:

#!/bin/bash
A=1.3141592653581 # variable 1
B=1.3141592653589 # variable 2
if (( `echo $A"<"$B | bc` )) ; then printf "$A is: < $B\n" ; else printf "$B is: < $A\n" ; fi ;
C=$(echo "$A+$B" | bc)
printf "C == $C\n" ;

Additional formatting for related numbers and types such as zero may be required; as addressed in some other postings eg: How to show zero before decimal point in bc?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!