Python:转换十六进制值:从大端到小端再到十进制
Python : Convert hex value : from big-endian to little endian and then to decimal
我正在读取文件并从文件中提取数据,我可以获取 ASCII 数据和整数数据。
我正在尝试将 8 个字节的数据从大端转换为小端,然后再转换为十进制值。
输入文件有这个数据
00 00 00 00 00 00 f0 3f
此值必须转换为 0x3ff0000000000000,因此 hex_to_double(0x3ff0000000000000) returns 值 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,)
我正在读取文件并从文件中提取数据,我可以获取 ASCII 数据和整数数据。
我正在尝试将 8 个字节的数据从大端转换为小端,然后再转换为十进制值。
输入文件有这个数据
00 00 00 00 00 00 f0 3f
此值必须转换为 0x3ff0000000000000,因此 hex_to_double(0x3ff0000000000000) returns 值 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,)