dinsdag 12 augustus 2008

convert bytes to an integer in python

ran into a situation where i had to convert some bytes to an integer value in python. This func does the trick. The mask is only used to have a counter of the same length counting backwards (hence the negation).
def bytesToInt ( self, bytes ):
""" convert certain amount of bytes to an integer """
size=0
i=0

mask = sys.maxint&(len(bytes)-1)
while i < len(bytes):
size = size|ord(bytes[i])<<((~i)&mask)*8
i+=1

return size

Geen opmerkingen: