msbin to ieee

revuesbio revuesbio at gmail.com
Mon May 7 08:00:02 EDT 2007


On 7 mai, 13:21, John Machin <sjmac... at lexicon.net> wrote:
> On May 7, 6:18 pm, revuesbio <revues... at gmail.com> wrote:
>
>
>
> > On 7 mai, 03:52, John Machin <sjmac... at lexicon.net> wrote:
>
> > > On May 7, 7:44 am, revuesbio <revues... at gmail.com> wrote:
>
> > > > Hi
> > > > Does anyone have the python version of the conversion from msbin to
> > > > ieee?
> > > > Thank u
>
> > > Yes, Google has it. Google is your friend. Ask Google. It will lead
> > > you to such as:
>
> > >http://mail.python.org/pipermail/python-list/2005-August/337817.html
>
> > > HTH,
> > > John
>
> > Thank you,
>
> > I've already read it but the problem is always present. this script is
> > for double precision MBF format ( 8 bytes).
>
> It would have been somewhat more helpful had you said what you had
> done so far,  even posted your code ...
>
> > I try to adapt this script for single precision MBF format ( 4 bytes)
> > but i don't find the right float value.
>
> > for example : 'P\xad\x02\x95' will return '0.00024924660101532936'
>
> If you know what the *correct* value is, you might like to consider
> shifting left by log2(correct_value/erroneous_value) :-)
>
> Do you have any known correct pairs of (mbf4 string, decimal_float
> value)? My attempt is below -- this is based on a couple of
> descriptive sources that my friend Google found, with no test data. I
> believe the correct answer for the above input is 1070506.0 i.e. you
> are out by a factor of 2 ** 32
>
> def mbf4_as_float(s):
>     m0, m1, m2, m3 = [ord(c) for c in s]
>     exponent = m3
>     if not exponent:
>         return 0.0
>     sign = m2 & 0x80
>     m2 |= 0x80
>     mant = (((m2 << 8) | m1) << 8) | m0
>     adj = 24 + 128
>     num = mant * 2.0 ** (exponent - adj)
>     if sign:
>         return -num
>     return num
>
> HTH,
> John

well done ! it's exactly what i'm waiting for !!

my code was:
>>> from struct import *
>>> x = list(unpack('BBBB','P\xad\x02\x95'))
>>> x
[80, 173, 2, 149]
>>> def conversion1(bytes):
b=bytes[:]
sign = bytes[-2] & 0x80
b[-2] |= 0x80
exp = bytes[-1] - 0x80 - 56
acc = 0L
for i,byte in enumerate(b[:-1]):
acc |= (long(byte)<<(i*8))
return (float(acc)*2.0**exp)*((1.,-1.)[sign!=0])

>>> conversion1(x)
0.00024924660101532936

this script come from google groups but i don't understand bit-string
manipulation (I'm a  newbie). informations about bit-string
manipulation with python is too poor on the net.

thank you very much for your script.
A.




More information about the Python-list mailing list