Search code examples
pythonfloating-pointintegerbit

How to reinterpret bits of float as int in python


I had to write code that printed out bits of floating point number (in hexadecimal). For C++, the first thing that came to mind was std::cout << std::hex << *reinterpret_cast<uint32_t*>(&x); where x is a floating point variable that stores the original number.

However, when I tried the same problem in python, I just couldn't come up with a python-ish way to solve it (using not built-in libraries is not allowed). My best attempts lead to something like this:

from ctypes import Union, c_uint32, c_float

class conversion(Union):
    _fields_ = [("int", c_uint32),
                ("float", c_float)]

v = conversion()
v.float = float(input())
print(hex(v.int)[2:])

which is basically C code.

So, is there more "python" way to do this? Did recent python versions introduce something that could be useful for this case?


Solution

  • Firstly, your implementation is inaccurate because float in CPython implementation is a double precision floating-point type (c++ double) so it's size is 64 bit. You have to use c_uint64 and c_double for best results

    You can use the struct module to pack float to Python bytes object and then unpack it to integer value:

    import struct
    float_to_hex = lambda f: hex(struct.unpack('@Q', struct.pack('@d', f))[0])
    print(float_to_hex(123.45)) # Output: 0x405edccccccccccd
    

    "Python" way: you can just use the float.hex() method but the result will be different:

    print(123.45.hex()) # Output: 0x1.edccccccccccdp+6