Search code examples
pythoncastinghexidl-programming-language

Convert hex string to float


I am trying to read from a file a bunch of hex numbers.

lines ='4005297103CE40C040059B532A7472C440061509BB9597D7400696DBCF1E35CC4007206BB5B0A67B4007AF4B08111B87400840D4766460524008D47E0FFB4ABA400969A572EBAFE7400A0107CCFDF50E'
dummy = [lines[index][i:i+16] for i in range(0, len(lines[index]),16)]
rdummy=[]
for elem in dummy[:-1]:
 
                rdummy.append(int(elem,16))

these are 10 number of 16 digits in particular when reading the first one, I have:

print(dummy[0])
4005297103CE40C0

now I would like to convert it to float

I have an IDL script that when reading this number gives 2.64523509

the command used in IDL is

double(4613138958682833088,0)

where it appers 0 is an offset used when converting.

is there a way to do this in python?


Solution

  • you probably want to use the struct package for this, something like this seems to work:

    import struct
    
    lines ='4005297103CE40C040059B532A7472C440061509BB9597D7400696DBCF1E35CC4007206BB5B0A67B4007AF4B08111B87400840D4766460524008D47E0FFB4ABA400969A572EBAFE7400A0107CCFDF50E'
    
    for [value] in struct.iter_unpack('>d', bytes.fromhex(lines)):
      print(value)
    

    results in 2.64523509 being printed first which seems about right