Extracting bit fields from an IEEE-784 float

Dan Stromberg drsalists at gmail.com
Mon Jul 30 12:52:21 EDT 2012


On Mon, Jul 30, 2012 at 12:44 AM, 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
>
>
> Questions:
>
> 1) Are there any known implementations or platforms where Python floats
> are not C doubles? If so, what are they?
>
Last I heard, DEC Alpha chips did not use IEEE floating point.


> 2) If the platform byte-order is reversed, do I need to take any special
> action? I don't think I do, because even though the float is reversed, so
> will be the bit mask. Is this correct?
>
> 3) Any other problems with the way I am doing this?
>
It gives me the heebie jeebies.  Why go to all the trouble and incur the
lack of portability to esoteric platforms, when you can just use arithmetic
expressions?  It's fancy, and it'll probably almost always work, but it's
probably not so wise.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120730/435d2cb2/attachment.html>


More information about the Python-list mailing list