how to reading binary data...

Peter Hansen peter at engcorp.com
Thu Oct 21 06:59:43 EDT 2004


marcos at nordesia.org wrote:
> SIGNIFICANCE = [0,1,2,3]  # this list is useful when reading bigendian longs
> #SIGNIFICANCE = [3,2,1,0] # this list is useful when reading littleendian
> longs
> 
> def str2long(s):
> 	"""Returns a long, using the first four byte of a string"""
> 	l = 0L # the long we will get
> 	for pos in SIGNIFICANCE: # get each byte in the order specified by the
> significance list
> 		if pos < len(s):
> 			c = s[pos]
> 		else:	# if we take a byte that is not in byte string (this happens at
> the end of file when file length is not multiple of 4.
> 			c = chr(0)
> 
> 		l*=0x100	# shift left 8 bits
> 		l+=ord(c)	# add the readed byte at the LSB.
> 
> 	return l

Ditch this!  It would be much easier, faster,
more maintainable to use the struct module:

    struct.unpack('<l', four_byte_string)

This returns an integer from little-endian data, while
using >l assumes big-endian data.

-Peter



More information about the Python-list mailing list