Skip to content

Instantly share code, notes, and snippets.

@wontonst
Created August 8, 2019 18:10
Show Gist options
  • Save wontonst/8696dcfb643121c864dec7c0d6ad26c5 to your computer and use it in GitHub Desktop.
Save wontonst/8696dcfb643121c864dec7c0d6ad26c5 to your computer and use it in GitHub Desktop.
interleave mortonize z order curve python bits
# http://code.activestate.com/recipes/577558-interleave-bits-aka-morton-ize-aka-z-order-curve/
def part1by1(n):
n&= 0x0000ffff
n = (n | (n << 8)) & 0x00FF00FF
n = (n | (n << 4)) & 0x0F0F0F0F
n = (n | (n << 2)) & 0x33333333
n = (n | (n << 1)) & 0x55555555
return n
def unpart1by1(n):
n&= 0x55555555
n = (n ^ (n >> 1)) & 0x33333333
n = (n ^ (n >> 2)) & 0x0f0f0f0f
n = (n ^ (n >> 4)) & 0x00ff00ff
n = (n ^ (n >> 8)) & 0x0000ffff
return n
def interleave2(x, y):
return part1by1(x) | (part1by1(y) << 1)
def deinterleave2(n):
return unpart1by1(n), unpart1by1(n >> 1)
def part1by2(n):
n&= 0x000003ff
n = (n ^ (n << 16)) & 0xff0000ff
n = (n ^ (n << 8)) & 0x0300f00f
n = (n ^ (n << 4)) & 0x030c30c3
n = (n ^ (n << 2)) & 0x09249249
return n
def unpart1by2(n):
n&= 0x09249249
n = (n ^ (n >> 2)) & 0x030c30c3
n = (n ^ (n >> 4)) & 0x0300f00f
n = (n ^ (n >> 8)) & 0xff0000ff
n = (n ^ (n >> 16)) & 0x000003ff
return n
def interleave3(x, y, z):
return part1by2(x) | (part1by2(y) << 1) | (part1by2(z) << 2)
def deinterleave3(n):
return unpart1by2(n), unpart1by2(n >> 1), unpart1by2(n >> 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment