reversing a mask
Eryk Vershen
eryk at unisoft.UUCP
Thu Nov 29 16:32:56 AEST 1984
Apropos of nothing here is a cute way to reverse bits due to C. Strachey.
int mask[] = {
0x55555555,
0x33333333,
0x0F0F0F0F,
0x00FF00FF,
0x0000FFFF
}
long
bitrev(val)
long val;
{
register long i;
register int j ,k;
i = val;
j = 16;
k = 4;
while (j) {
i = ((i & mask[k]) << j) | ((i >> j) & mask[k]);
j >>= 1;
k--;
}
return(i);
}
/*
* Proof of the above (by example).
*
* j=16 i=abcdefghijklmnopqrstuvwxyz012345
* 8 qrstuvwxyz012345abcdefghijklmnop
* 4 yz012345qrstuvwxijklmnopabcdefgh
* 2 2345yz01uvwxqrstmnopijklefghabcd
* 1 452301yzwxuvstqropmnklijghefcdab
* 0 543210zyxwvutsrqponmlkjihgfedcba
*/
--
- eryk vershen
ucbvax!unisoft!eryk
"overcoming computer literacy"
More information about the Comp.lang.c
mailing list