1

In Python, I need to convert a string to float where the string hex value as below

print(float.fromhex("c018dd8dad51d100"))

I got a value of:

1.3842057055291167e+19

but the same string in IEEE-754 calculator given some other negative value. My requirement is to match with IEEE-754 standard. Can anyone help me in this?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    What is exactly the other value that you are getting from the calculator? – sophros Feb 26 '20 at 10:08
  • 1
    Does this answer your question? [Convert hex to float](https://stackoverflow.com/questions/1592158/convert-hex-to-float) – sophros Feb 26 '20 at 10:16

1 Answers1

4

float.fromhex doesn't do what you think it does.

You can use binascii.unhexlify to convert from hex to bytes and then struct.unpack to convert from 8 IEEE-754 bytes to a double (it seems that your representation is big endian, so I've added >):

import binascii
import struct

# "d" is for double, > is for big endian, see https://docs.python.org/3/library/struct.html
value, = struct.unpack('>d', binascii.unhexlify(b'c018dd8dad51d100'))
Omer Tuchfeld
  • 2,886
  • 1
  • 17
  • 24