Search code examples
bashieee-754modbus

Convert HEX to IEEE 754 float


I am writing a bash script to interpret Modbus RTU messages in the Enron history format. The message is binary. I need to convert some of the bytes to 32bit floats. I want to use POSIX available programs or at least very commonly available ones. Bash, AWK, sed, od, etc.

Given 00b74e47 I have tried to use od but I am expecting 52919.000000. od is not giving me the result I am expecting.

echo -ne "\x00\xb7\x4e\x47" | od -tfD
0000000          5.91070985e-315
0000004

Solution

  • od -tfD converts to a double-precision floating-point number. od -tfF will convert to a single-precision floating-point number and will give the expected result.

    echo -ne "\x00\xb7\x4e\x47" | od -tfF
    0000000           52919
    0000004
    

    Hexdump can also be used. -e tells hexdump to output using a format string. 1/4 tells hexdump to use 4 bytes for the conversion. The %f is to output to a float.

    echo -ne "\x00\xb7\x4e\x47" | hexdump -e '1/4 "%f" "\n"'
    52919.000000