Search code examples
pythonfloating-pointbitwise-operators

Get the "bits" of a float in Python?


I am looking for the Python equivalent of Java's Float.floatToBits.

I found this Python: obtain & manipulate (as integers) bit patterns of floats but does anyone know of a less complicated way?


Solution

  • The answer that Alex Martelli gives in that question is really pretty simple -- you can reduce it to:

    >>> import struct
    >>> 
    >>> 
    >>> def floatToBits(f):
    ...     s = struct.pack('>f', f)
    ...     return struct.unpack('>l', s)[0]
    ...     
    ... 
    >>> floatToBits(173.3125)
    1127043072
    >>> hex(_)
    '0x432d5000'
    

    Once you have it as an integer, you can perform any other manipulations you need to.

    You can reverse the order of operations to round-trip:

    >>> def bitsToFloat(b):
    ...     s = struct.pack('>l', b)
    ...     return struct.unpack('>f', s)[0]
    
    >>> bitsToFloat(0x432d5000)
    173.3125