Skip to content

Instantly share code, notes, and snippets.

@ylg
Created February 27, 2011 19:30
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 ylg/846454 to your computer and use it in GitHub Desktop.
Save ylg/846454 to your computer and use it in GitHub Desktop.
Bit interleaving and de-interleaving in Ruby (also known as Morton Numbers.)
class Integer
def interleave(y)
x_bit_size = self > 0 ? Math.log2(self) : 1
y_bit_size = y > 0 ? Math.log2(y) : 1
z = 0
((((x_bit_size <=> y_bit_size) == -1) ? y_bit_size : x_bit_size).floor + 1).times do | i |
z |= (self & 1 << i) << i | (y & 1 << i) << (i + 1)
end
return z
end
def deinterleave
return 0, 0 if self == 0
x, y = 0, 0
((Math.log2(self)).floor + 1).times do | i |
if (0 != self & (1 << i))
(i & 1 == 0) ? x |= 1 << (i / 2) : y |= 1 << (i / 2)
end
end
return x, y
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment