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