You need to multiply it by 256 (2 8 ). Thus, the function will look something like this:
def pack (tup) : return 256*tup[1]+tup[0]
or perform a bit shift , which is more important when working with bits:
def pack(tup) : return (tup[1]<<8)|tup[0]
here << means that you put the value of tup[1] eight positions to the left. A pipe ( | ) means that you are performing an OR operation. This is reasonable if you follow values ββin a tuple less than 256 and can - at least theoretically - lead to some acceleration.
More general
If your tuple has an arbitrary length (for example, three, four or more elements), you can define a more general function:
def pack(tup) : sum = 0 for i in range(len(tup)) : sum |= tup[i]<<(i<<3) return sum
Here <<3 used as a shortcut to multiply by 8 , so the equivalent function would be:
def pack(tup) : sum = 0 for i in range(len(tup)) : sum |= tup[i]<<(8*i) return sum
Or written out, it's something like:
tup[0]|(tup[1]<<8)|(tup[2]<<16)|(...)
source share