Little explanation

Scott David Daniels Scott.Daniels at Acm.Org
Tue Mar 2 10:00:28 EST 2004


Angelo Secchi wrote:

> Hi,
> few days ago I had a problem of converting floating from an IBM/370
> system to the actual standard. Thanks to a couple of you (Anton and
> Howard) I got the code to solve the problem that as expected works fine.
> I (a newbie not only with Python but also with programming) tried to
> understand the code by myself but finally I decided to bother the list
> again for a couple of explanations. First here the code I'm referring
> to:
> 
> def ibm370tofloat(fourbytes):
>     i = struct.unpack('>I',fourbytes)[0]
>     sign = [1,-1][bool(i & 0x100000000L)]
>     characteristic = ((i >> 24) & 0x7f) - 64
>     fraction = (i & 0xffffff)/float(0x1000000L)
>     return sign*16**characteristic*fraction

This could also have been done as:

     def ibm370(fourbytes):
         first = ord(fourbytes[0])
         fraction = struct.unpack('>I', chr(0)+fourbytes[1:]) * 2. ** -24
         if first > 127: fraction = -fraction #or sign =[1,-1][first>127]
         characteristic = (first & 0x7F) - 64
         return fraction * 16 ** characteristic

Clearer?
-- 
-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list