decoding floats

Dean Hall ra9483 at email.sps.mot.com
Thu Nov 29 11:33:14 EST 2001


Nico Hartmann wrote:
> 
> > > Hi there,
> > >
> > > I look for a way to decode and encode float values into byte arrays.
> >
> > >>> import array
> > >>> a = array.array('f')
> > >>> a.append(42.42)
> > >>> a.tostring()
> > '\x14\xae)B'
> >
> > Something like this?
> 
> Yes, that would do. I figured out using the stuct.pack from struct package
> also works fine:
> 
> import struct
> bytes = struct.pack("d", 34.34)
> 
> Regards,
>  nico

The marshal module uses the same codec method as .pyc files.
Marshal might be easier and the output more readable:

	>>> import marshal
	>>> s = marshal.dumps(3.14)
	>>> s
	'f\x043.14'
	>>> marshal.loads(s)
	3.1400000000000001

And marshal is tolerant of trailing bytes:
	>>> marshal.loads(s + "bob")
	3.1400000000000001

The string s is:
	s[0] = 'f' 	indicates a float type follows.
	s[1] = 4   	the next 4 bytes contain a string describing the float.
	s[2:]= '3.14'	the ftoa() representation of the float.

!!Dean



More information about the Python-list mailing list