Calculating a 16-bit integer value from two 8-bit integers?

To illustrate what I mean: in a hex editor, I have 8C 01 , which is 396 little-endian. The data I'm working with is a tuple with two separate 8-bit integers i = (140, 1) .

To compute a 16-bit value, my first approach was to simply multiply the second integer by 255, then add the first. However, this method is simply incorrect, as it does not give the correct value (due to my lack of knowledge). Can anyone provide a better (possibly Pythonic) approach?

+5
source share
2 answers

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)|(...) 
+6
source

You must multiply by 256 ...

 >>> i[1]*256 + i[0] 396 

There is a Python method using the struct module, but not needed in such a simple case.

 >>> from struct import pack, unpack >>> unpack('<H', pack('BB', *i))[0] 396 
+6
source

Source: https://habr.com/ru/post/1237534/


All Articles