Exchange the bits at even and odd positions

Write code to exchange the bits at even and odd positions in a number.

Answer:


/**
* Program to exchange the bits at even and odd positions
* */
#include "stdio.h"
#include "stdlib.h"

void PrintBinary(size_t num)
{
for( int i = 31; i >=0; --i )
if ( num & ( 1 << i) )
printf("1");
else
printf("0");
printf("\n");
}

size_t SwapBits(size_t num)
{
/* Program to reverse the bits of a number */

return ( (num << 1) & 0xAAAAAAAA ) |
( (num >> 1 & 0x55555555) );
}

int main(int argc, char* argv[])
{
for ( int i = 1; i <= argc-1; ++i )
{
size_t num = atoi(argv[i]);
PrintBinary(num);
PrintBinary(SwapBits(num));
}
return 0;

}

No comments: