Bit twiddling floating point numbers

Mark Dickinson dickinsm at gmail.com
Wed Mar 5 16:06:37 EST 2008


On Mar 5, 3:25 pm, "Jeff.Goldfin... at gmail.com"
<Jeff.Goldfin... at gmail.com> wrote:
> I can pack and unpack a float into a long
> e.g.
> struct.unpack('I',struct.pack('f',0.123))[0]
> but then I'm not sure how to work with the resulting long.
>
> Any suggestions?

One alternative to using struct is to use math.ldexp and math.frexp:

>>> m, e = frexp(pi)
>>> m
0.78539816339744828
>>> e
2
>>> int(m*2**53)
7074237752028440L

Then you can do your bit twiddling on int(m*2**53), before using
ldexp to 'repack' the float.

Mark



More information about the Python-list mailing list