i am interested on this problem
Interleave bits the obvious way
(from http://graphics.stanford.edu/~seander/bithacks.html)
unsigned short x; // Interleave bits of x and y, so that all of the unsigned short y; // bits of x are in the even positions and y in the odd; unsigned int z = 0; // z gets the resulting Morton Number. for (int i = 0; i < sizeof(x) * CHAR_BIT; i++) // unroll for more speed... { z |= (x & 1U << i) << i | (y & 1U << i) << (i + 1); }
can someone explain to me how this works with an example?
for example if we have x = 100101 and y = 010101, what will be result?
Bit interleaving essentially takes two
nbit input numbers and produces one2nbit output number that alternately takes bits from the two input numbers. That is, bits from one number goes into the odd indices, and bits from the other goes into the even indices.So for your specific example:
Here we use the convention that bits from
xgoes into the even indices (0, 2, 4…) and bits fromygoes into the odd indices (1, 3, 5…). That is, bit interleaving is not a commutative operation;interleave(x, y)is generally not equal tointerleave(y, x).You can also generalize the bit interleaving operation to involve more than just 2 numbers.
Bit-interleaved numbers exhibit structural properties that can be taken advantage of in many important spatial algorithms/data structures.
See also
Related questions
“Obvious” algorithm
The algorithm essentially goes through every bits of the input numbers, checking if it’s 1 or 0 with bitwise-and, combining the two bits with bitwise-or, and concatenating them together with proper shifts.
To understand how the bits are rearranged, just work on a simple 4-bit example. Here
xidenotes thei-th (0-based) bit ofx.Once you convinced yourself that the mapping pattern is correct, implementing it is simply a matter of understanding how bitwise operations are performed.
Here’s the algorithm rewritten in Java for clarity (see also on ideone.com):
See also