Extracting bit fields from an IEEE-784 float

Dan Sommers dan at tombstonezero.net
Sun Jul 29 21:08:14 EDT 2012


On 2012-07-30 at 00:44:04 +0000,
Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:

> I wish to extract the bit fields from a Python float, call it x. First I 
> cast the float to 8-bytes:
> 
> s = struct.pack('=d', x)
> i = struct.unpack('=q', s)[0]
> 
> Then I extract the bit fields from the int, e.g. to grab the sign bit:
> 
> (i & 0x8000000000000000) >> 63

> 3) Any other problems with the way I am doing this?

No, but perhaps this would be clearer:

    import math
    sign = math.copysign(1.0, x)

There are solutions that use math.frexp, too, but IMO they're more
obtuse.

HTH,
Dan



More information about the Python-list mailing list