我正在读取文件并从文件中提取数据,我可以获取 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/