将 HEX 转换为 IEEE 754 浮点数
Convert HEX to IEEE 754 float
我正在编写一个 bash 脚本来解释 Enron 历史格式的 Modbus RTU 消息。消息是二进制的。我需要将一些字节转换为 32 位浮点数。我想使用 POSIX 可用的程序或至少是非常常用的程序。 Bash、AWK、sed、od 等
鉴于 00b74e47,我尝试使用 od,但我期待 52919.000000。 od 没有给我预期的结果。
echo -ne "\x00\xb7\x4e\x47" | od -tfD
0000000 5.91070985e-315
0000004
像这样?
$ crackNum --sp 436A508C
3 2 1 0
1 09876543 21098765432109876543210
S ---E8--- ----------F23----------
Binary: 0 10000110 11010100101000010001100
Hex: 436A 508C
Precision: SP
Sign: Positive
Exponent: 7 (Stored: 134, Bias: 127)
Hex-float: +0x1.d4a118p7
Value: +234.31464 (NORMAL)
您可以围绕 crackNum
编写包装器以摆脱 0x
或 post 处理输出。
crackNum
是一个Haskell程序,你可以从hackage下载:http://hackage.haskell.org/package/crackNum
使用 GNU 调试器:
gdb --batch -ex "print/f (float *) 0x436A508C"
输出:
= 234.314636
来源:Using the linux command line in bash as a programmer's calculator
如果 python3
是您的选择,请尝试以下操作:
echo "436a508c" | python3 -c 'import struct; print(struct.unpack("!f", bytes.fromhex(input()))[0])'
产量:
234.31463623046875
希望对您有所帮助。
od -tfD 转换为双精度浮点数。 od -tfF 将转换为单精度浮点数并给出预期结果。
echo -ne "\x00\xb7\x4e\x47" | od -tfF
0000000 52919
0000004
也可以使用Hexdump。 -e 告诉 hexdump 使用格式字符串输出。 1/4 告诉 hexdump 使用 4 个字节进行转换。 %f 是输出到一个浮点数。
echo -ne "\x00\xb7\x4e\x47" | hexdump -e '1/4 "%f" "\n"'
52919.000000
我正在编写一个 bash 脚本来解释 Enron 历史格式的 Modbus RTU 消息。消息是二进制的。我需要将一些字节转换为 32 位浮点数。我想使用 POSIX 可用的程序或至少是非常常用的程序。 Bash、AWK、sed、od 等
鉴于 00b74e47,我尝试使用 od,但我期待 52919.000000。 od 没有给我预期的结果。
echo -ne "\x00\xb7\x4e\x47" | od -tfD
0000000 5.91070985e-315
0000004
像这样?
$ crackNum --sp 436A508C
3 2 1 0
1 09876543 21098765432109876543210
S ---E8--- ----------F23----------
Binary: 0 10000110 11010100101000010001100
Hex: 436A 508C
Precision: SP
Sign: Positive
Exponent: 7 (Stored: 134, Bias: 127)
Hex-float: +0x1.d4a118p7
Value: +234.31464 (NORMAL)
您可以围绕 crackNum
编写包装器以摆脱 0x
或 post 处理输出。
crackNum
是一个Haskell程序,你可以从hackage下载:http://hackage.haskell.org/package/crackNum
使用 GNU 调试器:
gdb --batch -ex "print/f (float *) 0x436A508C"
输出:
= 234.314636
来源:Using the linux command line in bash as a programmer's calculator
如果 python3
是您的选择,请尝试以下操作:
echo "436a508c" | python3 -c 'import struct; print(struct.unpack("!f", bytes.fromhex(input()))[0])'
产量:
234.31463623046875
希望对您有所帮助。
od -tfD 转换为双精度浮点数。 od -tfF 将转换为单精度浮点数并给出预期结果。
echo -ne "\x00\xb7\x4e\x47" | od -tfF
0000000 52919
0000004
也可以使用Hexdump。 -e 告诉 hexdump 使用格式字符串输出。 1/4 告诉 hexdump 使用 4 个字节进行转换。 %f 是输出到一个浮点数。
echo -ne "\x00\xb7\x4e\x47" | hexdump -e '1/4 "%f" "\n"'
52919.000000