Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: %a format

Reply
Thread Tools

Re: %a format

 
 
Jeff Epler
Guest
Posts: n/a
 
      09-08-2004
# 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-----

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Money Format + Decimal Place Format shannon Java 1 02-02-2006 03:47 PM
Money Format + Decimal Place Format shannon Java 0 02-01-2006 10:02 PM
need code to convert float format to internal java float format which is kept in 4 bytes integer Andy Java 7 05-10-2004 09:26 PM
NTFS quick format and normal format Guan Foo Wah MCSE 2 05-08-2004 11:35 PM
Date Format - best way of converting a string into a date format Brian Candy ASP .Net 2 02-18-2004 02:13 PM



Advertisments