[Nottingham] A Little Coding Gem
Martin
martin at ml1.co.uk
Thu Nov 15 18:05:40 UTC 2012
Folks,
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 :-) )
More to the point, why would you want to do that?!
For example, the above reminds of a neat little trick in Z80 assembler
to use the "DAA" (Decimal Adjust Accumulator) to neatly encode/decode
ASCII hex characters...
and 15
add a,90h
daa
adc a,40h
daa
The original intention for the DAA instruction was to support BCD
arithmetic...
Any other similar fun obscure beauties?
Cheers,
Martin
DAA:
http://z80-heaven.wikidot.com/instructions-set:daa
BCD:
http://en.wikipedia.org/wiki/Binary-coded_decimal
--
- ------------------ - ----------------------------------------
- Martin Lomas - OpenPGP (GPG/PGP) Public Key: 0xCEE1D3B7
- martin @ ml1 co uk - Import from hkp://subkeys.pgp.net or
- ------------------ - http:// ml1 .co .uk/martin_ml1_co_uk.gpg
More information about the Nottingham
mailing list