How can I do bit operation on python float value

Miles semanticist at gmail.com
Mon Mar 23 06:42:41 EDT 2009


On Mon, Mar 23, 2009 at 2:44 AM, valpa wrote:
> I have a python float 1.2345678. I know that it is stored as a double
> in C type. And I know it actually is 1010101010101 -like format. Then
> I want to do some bit operation on it. How?
>
> Sure, I want a float output when I finish the operation.

Just for fun:

>>> import ctypes
>>> def cast(value, to_type):
...     return ctypes.cast(ctypes.pointer(value), ctypes.POINTER(to_type))[0]
...
>>> def float_to_int(x):
...     return cast(ctypes.c_double(x), ctypes.c_uint64)
...
>>> def int_to_float(x):
...     return cast(ctypes.c_uint64(x), ctypes.c_double)
...
>>> float_to_int(5)
4617315517961601024
>>> bin(float_to_int(5))
'0b100000000010100000000000000000000000000000000000000000000000000'
>>> int_to_float(float_to_int(5) & float_to_int(10))
2.5

-Miles



More information about the Python-list mailing list