Obtain & manipulate bit pattern of float as integer

前端 未结 5 1792
抹茶落季
抹茶落季 2020-12-09 19:05

In Python 2.5, I have a float and I\'d like to obtain and manipulate its bit pattern as an integer.

For example, suppose I have

x = 173.3125
<         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 19:35

    The problem is that a Python float object might not be a IEEE 754, because it is an object (in fact they are, but internally they could hold whichever representation is more convenient)...

    As leo said, you can do a type cast with ctypes, so you are enforcing a particular representation (in this case, single precision):

    from ctypes import *
    x = 173.3125
    bits = cast(pointer(c_float(x)), POINTER(c_int32)).contents.value
    print hex(bits)
    #swap the least significant bit
    bits ^= 1
    

    And then back:

    y = cast(pointer(c_int32(bits)), POINTER(c_float)).contents.value
    

提交回复
热议问题