IBM integer and double formats

Mark Dickinson dickinsm at gmail.com
Mon Nov 10 23:00:22 CET 2008


On Nov 10, 7:20 pm, "john.goodleaf" <john.goodl... at gmail.com> wrote:
> my own routines, does anyone know of an already-done means of writing
> integers and floats out to their IBM mainframe equivalents?

Here's a quick attempt at converting doubles using Python.
It uses the isnan and isinf functions that are in Python 2.6;
if you don't have Python 2.6 or don't care about IEEE specials
then just delete the relevant lines.

Mark

def IBMtoIEEE(x):
    """Convert a Python float (assumed stored as an IEEE 754 double)
    to IBM hexadecimal float format.

    NaNs and infinities raise ValueError.  IEEE values that are too
    large to be stored in IBM format raise OverflowError.  Values that
    are too small to be represented exactly in IEEE format are rounded
    to the nearest IBM value, using round-half-to-even.

    The result is returned as a hex string.

    """
    if isnan(x) or isinf(x):
        raise ValueError("cannot convert infinity or nan to IBM
format")
    if not x:
        s, m, e = 0, 0, 0
    else:
        s = 0 if x > 0.0 else 1
        m, e = frexp(x)
        m, e = int(abs(m) * 2**(56 - -e % 4)), (e + -e % 4)//4 + 64
        if e >= 128:
            raise OverflowError("value too large to represent in IBM
format")
        elif e < 0:
            h = 2**(4*-e - 1)
            m = m // (2*h) + (1 if m & h and m & (3*h-1) else 0)
            e = 0
    return "%x" % (s*2**63 + e*2**56 + m)





More information about the Python-list mailing list