Newbie lost(new info)
Angelo Secchi
secchi at sssup.it
Sat Feb 28 11:50:22 EST 2004
Anton and Howard,
thank you very much (both your sample code do the job) I was really lost
into bit manipulation without any real hope of success!!
Angelo
On Sat, 28 Feb 2004 03:24:57 +0100
anton at vredegoor.doge.nl (Anton Vredegoor) wrote:
> Angelo Secchi <secchi at sssup.it> wrote:
>
> >>from binascii import hexlify
> >>inf = file('foo','rb')
> >>data = inf.read(1970)
> >>for i in range(223):
> >> index = i * 4 + 113
> >> print hexlify(data[index: index + 4])
> >
> >
> >46ee3bb4 (I know that this should be 15612852)
> >00000000 (I know that this should be 0)
> >00000000 (I know that this should be 0)
> >465de39a (I know that this should be 6153114)
> >00000000 (I know that this should be 0)
> >00000000 (I know that this should be 0)
>
> Based on this message:
>
> http://groups.google.com/groups?&selm=1993Aug25.074420.28786%40bhof01.ctg.nl
>
> I wrote a function that maybe could do it (use at own risk). It
> converts a 4-byte real from "IBM System/370 Floating Point Format" to
> a Python float. In your code above replace one line:
>
> >> print hexlify(data[index: index + 4])
>
> with:
>
> >> print ibm370tofloat(data[index: index + 4])
>
>
> The conversion function and a test function:
>
> import struct
>
> 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
>
> def test():
> import binascii
> pi = "413243f7"
> s1 = "46ee3bb4"
> s2 = "465de39a"
> for x in [pi,s1,s2]:
> y = binascii.unhexlify(x)
> print ibm370tofloat(y)
>
> if __name__=='__main__':
> test()
>
> output:
>
> 3.14159297943
> 15612852.0
> 6153114.0
>
> I hope this helps.
>
> Anton
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
--
========================================================
Angelo Secchi PGP Key ID:EA280337
========================================================
Current Position:
Graduate Fellow Scuola Superiore S.Anna
Piazza Martiri della Liberta' 33, Pisa, 56127 Italy
ph.: +39 050 883365
email: secchi at sssup.it www.sssup.it/~secchi/
========================================================
More information about the Python-list
mailing list