Converting IBM Floats..Help..

Jeff Epler jepler at unpythonic.net
Thu Mar 25 17:38:49 CET 2004


Note that Python floats are C doubles, which generally have a 53-bit
mantissa.  This means that not all ibm360 floats can be exactly
represented.  The exponent ranges may also not match up.  Finally, I
have no idea if ibm360 floats have special representations for cases
like denormal, NaN, infinity, etc. so these aren't handled.

Basically, the approach is to pull the bits out of the original string
and then do some arithmetic to turn them into floats.

I don't know anything about ibm360 format, but I followed your
description, and the test passes..

import struct

def ibm360_decode(s):
    l = struct.unpack(">Q", s)[0]
    sign = l >> 63
    exponent = (l >> 56) & 0x7f - 64
    mantissa = (l & ((1L<<56) - 1)) / (16. ** 14)
    return [1,-1][sign] * (16**exponent) * mantissa

def test():
    vectors = [
        (155, 'B\x9b\x00\x00\x00\x00\x00\x00'),
        (77, 'BM\x00\x00\x00\x00\x00\x00'),
        (1, 'A\x10\x00\x00\x00\x00\x00\x00'),
        (0, '\x00\x00\x00\x00\x00\x00\x00\x00'),
    ]

    for v, s in vectors:
        d = ibm360_decode(s)
        print v, d, `s`
        assert d == v

if __name__ == '__main__': test()




More information about the Python-list mailing list