All python integers are long under the hood (unless you're playing with bigger numbers).
To extract x and y, just reverse the steps of the above function.
def int_to_signed_short(value):
return -(value & 0x8000) | (value & 0x7fff)
def xy_from_index(index):
x, y = index & 65535, (index >> 16) + 16
return map(int_to_signed_short, [x, y])
In more detail, your function takes the two numbers and shifts them in binary so they don't overlap with each other.
x & 65535
only keeps the 16 rightmost bits of x
, since 65535 is 16 1s in binary. Read more about bitwise AND.
(y - 16) << 16
shifts the number y - 16
16 bits to the left. So if your number was XXXXX in binary, it will become XXXXX0000000000000000. Read more about bitwise shift.
A | B
will OR the bits of both numbers. Since A has 16 0s to the right and B is at most 16 bits long, A and B will not interfere with each other's bits. Read more about bitwise OR
Once you understand that, it should become clear how my function is the inverse of this.
Example
>>> index = index_from_xy(1234, 5678)
>>> index
371066066
>>> xy_from_index(index)
(1234, 5678)