Re: %a format

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

  1. Jeff Epler

    Jeff Epler Guest

    # 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
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Brian Candy
    Replies:
    2
    Views:
    1,182
    Janaka
    Feb 18, 2004
  2. Andy
    Replies:
    7
    Views:
    6,302
    Roedy Green
    May 10, 2004
  3. shannon
    Replies:
    1
    Views:
    8,621
  4. shannon
    Replies:
    0
    Views:
    583
    shannon
    Feb 1, 2006
  5. Replies:
    6
    Views:
    475
    Thomas Ganss
    Jan 15, 2006
Loading...

Share This Page