bits swap within a byte

Joel Sherrill joel.sherrill at oarcorp.com
Thu Jun 8 20:16:33 UTC 2006


Paul Evans wrote:

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

OK.. I have added to your post.  Attached is a test program which uses 
nibbles
to swap.  The magic is here.  The rest is test.

static uint8_t swapped_nibbles[16] = {
  0x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe,  0x1, 0x9, 0x5, 0xd, 0x3, 0xb, 
0x7, 0xf
};
static inline uint8_t swap_bits_table(uint8_t n) {
 return swapped_nibbles[(n&0xF0) >>4] | (swapped_nibbles[(n&0x0F)] << 4);
}

><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
>>
>>
>>    
>>
>
>
>  
>

-------------- next part --------------
A non-text attachment was scrubbed...
Name: sw.c
Type: text/x-csrc
Size: 1007 bytes
Desc: not available
URL: <http://lists.rtems.org/pipermail/users/attachments/20060608/0c60e734/attachment-0001.bin>


More information about the users mailing list