bits swap within a byte

Paul Evans paule at martexdesign.com
Thu Jun 8 18:40:55 UTC 2006


Hi,

I couldn't resist this. I made a few changes to the snippet (mostly
cosmetic) to fix it:

<CODE>
static inline uint8_t swap_bits(uint8_t n) {
  n = ((n&0xF0) >>4 ) | ( (n&0x0F) <<4);
  n = ((n&0xCC) >>2 ) | ( (n&0x33) <<2);
  n = ((n&0xAA) >>1 ) | ( (n&0x55) <<1);

  return  n;
};
</CODE>

My test driver:
 
<CODE>
void test(uint8_t b) {
     printf("swapping %2.2x into %2.2x\n", b, swap_bits(b));     
};
     
int main(int argc, char *argv[])
{
    test(0x0f);    test(0xff);
    test(0x01);    test(0x02);   
    test(0x04);    test(0x08);   
    test(0x55);    test(0xaa);
</CODE>

The output:

<CODE>
swapping 0f into f0
swapping ff into ff
swapping 01 into 80
swapping 02 into 40
swapping 04 into 20
swapping 08 into 10
swapping 55 into aa
swapping aa into 55
Press any key to continue . . .
</CODE>

End of overkill mode. Back to work..

	-Paul


-----Original Message-----
From: Joel Sherrill [mailto:joel.sherrill at oarcorp.com] 
Sent: Thursday, June 08, 2006 1:25 PM
To: Kate Feng
Cc: rtems-users at rtems.com
Subject: Re: bits swap within a byte

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:

http://graphics.stanford.edu/~seander/bithacks.html

And at 
http://www.ocf.berkeley.edu/~wwu/cgi-bin/yabb/YaBB.cgi?board=riddles_cs;acti
on=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.

--joel

> Thanks,
> Kate
>
>





More information about the users mailing list