简体   繁体   English

如何将十六进制字符串转换为解压缩的IEEE 754格式编号: -

[英]How to convert a hex-string into an unpacked IEEE 754 format number:-

using Python 2.7.3: How to convert a hex-string into an unpacked IEEE 754 format number:- 使用Python 2.7.3:如何将十六进制字符串转换为解压缩的IEEE 754格式编号: -

I have a string of hex data in this form: 我有一个这种形式的十六进制数据字符串:

data = '38 1A A3 44'

I would like to convert this to a floating point number by using struct.unpack: 我想通过使用struct.unpack将其转换为浮点数:

fdata = struct.unpack('<f','\x38\xA1\xA3\x44')  # fdata=1304.8193359375

Is there a Pythonic solution or do I need to somehow substitute an escape sequence for each space in data ? 是否有Pythonic解决方案或者我是否需要以某种方式替换数据中每个空间的转义序列?

Convert the hex codepoints to a byte string first; 首先将十六进制代码点转换为字节串; binascii.unhexlify() can do this for you, provided you remove the whitespace: 如果删除空格, binascii.unhexlify()可以为您执行此操作:

import binascii
import struct

fdata = struct.unpack('<f', binascii.unhexlify(data.replace(' ', '')))[0]

Demo: 演示:

>>> import binascii
>>> import struct
>>> data = '38 1A A3 44'
>>> struct.unpack('<f', binascii.unhexlify(data.replace(' ', '')))
(1304.8193359375,)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM