1

I couldn't find a working answer for the conversion of an hex to float value. Starting from this answer for converting a float to an hex float to hex, would you know how I can then convert that same hex to the original float back again?

shin
  • 333
  • 3
  • 11
  • Take a look at IEEE-754. – user1091344 Dec 09 '22 at 12:14
  • I see at least two different hex encodings in [that Q&A](https://stackoverflow.com/questions/23624212/how-to-convert-a-float-into-hex): one is packing the IEEE 754 binary representation, the other is base 16 scientific notation. Please be specific about which one to use. – Ruud Helderman Dec 09 '22 at 12:39
  • A correct answer for this question depends on your use case. If you're transferring data, converting to/from a hex string may not be an efficient way of doing that. – Ouroborus Dec 09 '22 at 12:53
  • @Ouroborus how would you do that in that case? – shin Dec 09 '22 at 13:15

1 Answers1

1

Same thing but in reverse:

import struct

def float_to_hex(f):
    return hex(struct.unpack('<I', struct.pack('<f', f))[0])

def hex_to_float(h):
    return struct.unpack('<f', struct.pack('<I', int(h, 16)))[0]

def double_to_hex(f):
    return hex(struct.unpack('<Q', struct.pack('<d', f))[0])

def hex_to_double(h):
    return struct.unpack('<d', struct.pack('<Q', int(h, 16)))[0]

(Notes: Python 3 doesn't add the L to longs. float_to_hex and double_to_hex come from this answer.)

Ouroborus
  • 16,237
  • 4
  • 39
  • 62