4

I want to change the float to hex and hex to float.

So I want to get equal of the first float and end of the float.

This is what I tried, on Python 2.7; f1 = first float, h = hex string, f2 = new float value from the hex string.

f1 = 15.3
h=f1.hex() #0x1.e99999999999ap+3

How can I change the h hex string to a float again?

I've tried

f2 = int(h,16)
f2 = float(h)
f2 = h.float()

but none of those work.

I can also use Python 3.5 if that helps.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • For conversion from `any base to any base` with `decimal point`, you will have to create your own **custom code**. I don't think there are any modules for this. – Kaushik NP Sep 27 '17 at 11:17
  • here : https://stackoverflow.com/questions/23624212/how-to-convert-a-float-into-hex and here : https://stackoverflow.com/questions/1592158/convert-hex-to-float – Dadep Sep 27 '17 at 11:19
  • @Dadep: those cover C binary standards, not the hex format returned by `float.hex()`. – Martijn Pieters Sep 27 '17 at 11:22
  • oh sorry... thanks, I'm learning something new. I didn't know that ! – Dadep Sep 27 '17 at 11:24

1 Answers1

6

Use the float.fromhex() classmethod:

>>> float.fromhex(h)
15.3

This is the direct inverse of the float.hex() instance method.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343