user301016
user301016

Reputation: 2237

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

I am reading a file and extracting the data from the file, I could able to fetch the ASCII data and integer data.

I am trying to convert 8 bytes of data from Big endian to Little endian and then to decimal value.

Input file has this data

00 00 00 00 00 00 f0 3f

This value has to be converted to 0x3ff0000000000000, so that hex_to_double(0x3ff0000000000000) returns value 1.0

The code I am trying to convert the above value to little-endian and to decimal is

# 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]

Any suggestions shall be helpful.

Upvotes: 1

Views: 6240

Answers (1)

abhilb
abhilb

Reputation: 5757

Your data is already in base16. So you should first convert it to binary format and then unpack to decimal like this:

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

Upvotes: 2

Related Questions