Skip to content

Instantly share code, notes, and snippets.

@torsten
Created April 1, 2011 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torsten/897977 to your computer and use it in GitHub Desktop.
Save torsten/897977 to your computer and use it in GitHub Desktop.
Calculates z-ordered values from x and y coordinates.
def z_order(x, y):
"""Creates a z-order value from the 15 least significant bits of
the `int`s `x` and `y`.
http://en.wikipedia.org/wiki/Z-order_curve
"""
z = 0
for bit_pos in range(15):
z |= (x & (1 << bit_pos)) << bit_pos
z |= (y & (1 << bit_pos)) << (bit_pos + 1)
return z
if __name__ == '__main__':
def test(x, y, z):
assert z_order(x, y) == z, \
"Expected %s, got %s." % (bin(z), bin(z_order(x, y)))
test(0b0, 0b0, 0b0)
test(0b1, 0b1, 0b11)
test(0b0, 0b1, 0b10)
test(0b100, 0b001, 0b010010)
test(0b1111, 0b1111, 0b11111111)
test(0b1111, 0b0000, 0b01010101)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment