extracting hex mant+exp from double?

Tim Peters tim.one at home.com
Sun Jun 10 00:12:42 EDT 2001


[thinkit]
> python docs say floats are all doubles...which usually (i think
> always) is the IEEE spec for 8-byte float.  are there any routines
> out there to extract the binary mantissa and exponent...or better
> hexadecimal mantissa and exponent out of the float?  i want to do
> some statistics but don't want to use decimal.  i know you can
> access the 8 bytes with struct lib...then do some bit manipulations
> to do the trick.  has anybody done this already?

Sorry, it's unclear what you want.  How about you pretend the routine you
want already existed, and give us a specific example showing exactly what it
is you want this routine to accept as argument(s) and return as result(s)?

It's not even clear to me that you really want to pick at the bits.  Have
you tried, for example, math.frexp?

>>> import math
>>> math.frexp(1.0)
(0.5, 1)
>>> math.frexp(2.**100)
(0.5, 101)
>>> math.frexp(.125)
(0.5, -2)
>>>

That picks apart the mantissa and exponent in a useful way.  If you then
want, say, the mantissa as a 53-bit integer shown as a hex string,

>>> math.frexp(.1)
(0.80000000000000004, -3)
>>> m = _[0]
>>> m
0.80000000000000004
>>> m * 2L**53
7205759403792794.0
>>> long(_)
7205759403792794L
>>> hex(_)
'0x1999999999999AL'
>>>





More information about the Python-list mailing list