Created
February 27, 2011 19:30
-
-
Save ylg/846454 to your computer and use it in GitHub Desktop.
Bit interleaving and de-interleaving in Ruby (also known as Morton Numbers.)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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