# Re: %a format

Discussion in 'Python' started by Jeff Epler, Sep 8, 2004.

1. ### Jeff EplerGuest

# This file is in the public domain
import random,math, struct

def hexf(d):
q, = struct.unpack("Q", struct.pack("d", d))
man = q & 0xfffffffffffff
sgn = ["", "-"][q >> 63]
bexp = (q >> 52) & 0x7ff
exp = bexp - 0x3ff
esgn = ["+", "-"][exp < 0]
if bexp == 0x7ff:
# SNan, QNan, or infinity
return str(d)
elif bexp == 0x0:
# Denormal or zero
if not man:
return "%s0X0P0" % sgn
imp = 1l<<52
exp += 1
while not man & imp:
man <<= 1
exp -= 1
else:
man = man + (1l<<52)
hman = hex(man)[2:-1]
hman = hman.rstrip("0")
if len(hman) == 1:
return "%s0X%sP%d" % (sgn, hman, exp)
else:
return "%s0X%s.%sP%d" % (sgn, hman[0], hman[1:], exp)

def test():
inf = float("inf"); ninf = -inf
nan = float("nan"); nnan = -nan
pairs = [
(0, "0X0P0"),
(-1.*0, "-0X0P0"),
(1, "0X1P0"),
(.5, "0X1P-1"),
(2, "0X1P1"),
(1.5, "0X1.8P0"),
(2.**10, "0X1P10"),
(2.**-10, "0X1P-10"),
(2.**-320, "0X1P-320"),
(2.**-1024, "0X1P-1024"),
(2.**-1060, "0X1P-1060"),
(2.**1020, "0X1P1020"),
(-1, "-0X1P0"),
(-.5, "-0X1P-1"),
(1-2.**-53, "0X1.FFFFFFFFFFFFFP-1"),
(-2, "-0X1P1"),
(-1.5, "-0X1.8P0"),
(-2.**10, "-0X1P10"),
(-2.**-10, "-0X1P-10"),
(-2.**-320, "-0X1P-320"),
(-2.**-1024, "-0X1P-1024"),
(-2.**-1060, "-0X1P-1060"),
(-2.**1020, "-0X1P1020"),
(-(1-2.**-53), "-0X1.FFFFFFFFFFFFFP-1"),
(inf, str(inf)),
(ninf, str(ninf)),
(nan, str(nan)),
(nnan, str(nnan)),
]
success = 0
for f, s in pairs:
t = hexf(f)
print repr(f), t
if t != s:
print "FAIL", f, s, t
else:
success += 1
if success == len(pairs):
print "SUCCESS", success

if __name__ == '__main__': test()

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)

iD8DBQFBP2u7Jd01MZaTXX0RAjpqAJ9eUcoK7vNnhNKD/U5jULmPMEwNEACfR8eY
VBm9j+WGfxH/GJUwYmvFT/s=
=BTiP
-----END PGP SIGNATURE-----

Jeff Epler, Sep 8, 2004