python : Convert hex value : from big-endian to little endian and then to decimal

标签 python hex

我正在读取文件并从文件中提取数据,我可以获取 ASCII 数据和整数数据。

我正在尝试将 8 字节数据从 Big endian 转换为 Little endian,然后转换为十进制值。

输入文件具有此数据

00 00 00 00 00 00 f0 3f

该值必须转换为 0x3ff0000000000000,以便 hex_to_double(0x3ff0000000000000) 返回值 1.0

我尝试将上述值转换​​为小端和十进制的代码是

# Get the Scalar value
file.seek(0, 1)
byte = file.read(8)
hexadecimal = binascii.hexlify(byte)
hexaValue = byte.hex()
print(" hexadecimal 1 : %s"% struct.pack('<Q', int(hexadecimal, base=16)))


**# unable to convert the value to the int, so that it can be passed to **hex_to_double** function**

# wrote this function to convert the int value to decimal value
def hex_to_double(h):
    return struct.unpack('<d', struct.pack('<Q', h))[0]

任何建议都会有帮助。

最佳答案

您的数据已采用 base16 格式。因此,您应该首先将其转换为二进制格式,然后解压为十进制格式,如下所示:

>>> data = binascii.unhexlify(b'000000000000f03f')
>>> data
b'\x00\x00\x00\x00\x00\x00\xf0?'
>>> struct.unpack('<d', data)
(1.0,)

关于 python : Convert hex value : from big-endian to little endian and then to decimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59153523/

相关文章:

python - pip 说模块 "weren' t 找到“要卸载,但 pip 列表显示它们

python - 返回 True 和 None 与 True 和 False 是 Pythonic 吗?

python - 过滤 MultiIndex Pandas DataFrame

mysql - 带有十六进制文字的 JDBCPreparedStatement

c - C语言中如何反转一个整数?

c - Control+问号的十六进制代码?

python - 当我运行同一个 tensorflow-r1.0 程序两次时出现不同的错误

python - virtualenv 不干扰 #!/usr/bin/env python

Python 字符串操作。第五位加一个角色

python - 通过十六进制字符串迭代