python-3.xfloating-pointnumber-systems

Decimal float number to Hexadecimal in Python


I am trying to convert a floating point number from decimal to hexadecimal. But I am not getting in the format I want. For example, if the decimal number is 54.75, I want the hexadecimal in the format 36.C0 However, I am not able to convert it to this format.

float.hex(54.75)

gives 0x1.b600000000000p+5

Python built-in function hex() also doesn't support float numbers.


Solution

  • As stated in the comments, you can split the number into various parts and then combine the converted results. For example:

    import math
    import re
    
    
    def get_hex(n):
        assert not math.isinf(n)
        assert not math.isnan(n)
    
        for sign, a, b in re.findall(r"(-?)(\d+)\.?(\d*)", str(n)):
            if b:
                return f"{sign}{int(a):X}.{int(256 * float('0.' + b)):>02X}"
            else:
                return f"{sign}{int(a):X}"
    
    
    print(get_hex(54.05))
    print(get_hex(54.50))
    print(get_hex(54.75))
    print(get_hex(15))
    print(get_hex(-15))
    print(get_hex(-15.21))
    print(get_hex(100_000_000_000.15))
    

    Prints:

    36.0C
    36.80
    36.C0
    F
    -F
    -F.35
    174876E800.26