Swap even-odd bits of a number

This program is to swap Even and Odd position of a number.

  • Logic:
  • Get all the bits at the even position.
  • And the number with 10 as 10 = 1 0 1 0
  • Get all the bits at odd position
  • And the number by 5 = 0 1 0 1
  • Now do left shift for even and right shift for odd
  • OR the result.

Implementation:

#include <stdio.h>
#define MAX_BIT (sizeof(int) * 8)

int display_binary(unsigned int num)
{
   int i;
   for(i= MAX_BIT-1;i>=0;i--)
   {
       if((num >> i)&1)
         printf("1");
       else
         printf("0");
   }
}
    
int swap_even_odd(int num)
{
    int even = num & 0XAAAAAAAA;
    int odd = num & 0X55555555;
    
    even = even>>1;
    odd = odd <<1;
    
    return (even | odd);
}

int main()
{
  int num;
  printf("\n Enter the number: ");
  scanf("%d", &num);
  printf("\n Number before swapping is: %d binary::", num);
  display_binary(num);
  
  int res = swap_even_odd(num);
  printf("\n Number after swapping is: %d binary::", res);
  display_binary(res);
  
  return 0;
}

Output:

Enter the number: 23

 Number before swapping is: 23 binary::00000000000000000000000000010111
 Number after swapping is: 43 binary:00000000000000000000000000101011


Categories: Data Structure and Algorithm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: