bits swap within a byte

Joel Sherrill joel.sherrill at
Thu Jun 8 17:25:08 UTC 2006

Kate Feng wrote:

> Is there any elegant built-in macro which does bits swap
> within each byte or other alternatives ?  For example,
> bit 0 <-> bit 7, bit 1 <->bit 6, bit 2 <->bit 5, bit3 <->bit 4 ?
I would this link on Google with multiple algorithms:

And at;action=display;num=1103355188
I found this code snippet which looks promising. 
n = n&11110000 >>4 | n&00001111 << 4;
n = n&11001100 >>2 | n&00110011 << 2;
return  n&10101010 >>1 | n&01010101 << 1;

I am not sure the bit constants are specified correctly though.  Looks 
like some would be turned to octal and others
to decimal to me.  Better to convert them to hex and be sure.  Might as 
well as parentheses as well.

It can be faster to do a table lookup.   Rather than a 256 entry table, 
tt should be possible to work on nibbles and
then use a 16 entry table to swap the nibble values.


> Thanks,
> Kate

More information about the users mailing list