[Nottingham] A Little Coding Gem
nick at leverton.org
Fri Nov 16 13:05:53 UTC 2012
On Thu, Nov 15, 2012 at 06:08:24PM +0000, Martin wrote:
> Fortune has just served up a little beauty for me just now:
> n = ((n >> 1) & 0x55555555) | ((n << 1) & 0xaaaaaaaa);
> n = ((n >> 2) & 0x33333333) | ((n << 2) & 0xcccccccc);
> n = ((n >> 4) & 0x0f0f0f0f) | ((n << 4) & 0xf0f0f0f0);
> n = ((n >> 8) & 0x00ff00ff) | ((n << 8) & 0xff00ff00);
> n = ((n >> 16) & 0x0000ffff) | ((n << 16) & 0xffff0000);
> -- Yet another mystical 'C' gem. ...
> Anyone like to guess or even work out what it does? :-> (Evil grin :-) )
Far too lazy for the latter here, that would involve the sort of real
work that I'm avoiding by reading the list :-) I guessed some sort of
CRC but I see others have given a more accurate answer.
> More to the point, why would you want to do that?!
To save space and/or time and/or registers and/or cache and/or brainpower
(by monkey-copying soemone else's code), delete where not applicable ?
There are loads of techniques to achieve the sort of bit-twiddling
where you (or at least I) sometimes think "how can I do that neatly"
But on the rare occasions I need one, at least I comment where it came
from and how it (allegedly) works !
More information about the Nottingham