Hex to float and float to hex
Question:
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?
Answers:
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.)
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?
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.)