Reputation: 7479
I'm searching for a simple algorithm that 'combines' two 2bytes integers into one unique 4bytes integer.
The two 2bytes integers are both whole positive numbers in the range 0..65535
.
I want to create one 4bytes integer that is the exact combination of both, in a way that will make it easy to:
(1) given the two 2bytes integers --> calculate the value of that 4bytes integer.
(2) given the 4bytes integer --> parse the contents of the two 2bytes integers.
Any idea how to achieve this in python
?
Upvotes: 3
Views: 557
Reputation: 799150
>>> i1, i2 = 345, 12
>>> i1 * 0x10000 + i2
22609932
>>> divmod(22609932, 0x10000)
(345, 12)
Upvotes: 8
Reputation: 31061
How about:
def combine(n, m):
return (n << 16) | m
def extract(c):
return (c >> 16), c & 0xffff
This solution places one of the 2-byte integers in the upper half of a 32-bit word, and the other into the lower half. In order to extract the values, simply take the upper half of the word (c >> 16
), and the lower half (c & 0xffff
).
Upvotes: 16