# Swap odd-odd and even-even

This program is for swapping odd bits with its next odd bits and even bits with its next even bits

LOGIC:
If the two bits are different, just toggle them

odd bit condition : i %2 ==0
even bit condition : i %2 ==1

Example:
Number 22
0 0 0 1 0 1 1 0
Swap odd = 0 1 0 0 0 0 1 1
Swap even= 0 1 0 0 1 0 0 1
Thus number is : 73

``````#include <stdio.h>
#define MAX_BITS 8

int swap_bits(int num,int bit1 ,int bit2)
{
num =num ^ (1 << bit1);
num= num ^ (1 << bit2);
return num;
}

int swap_odd_odd_even_even (int n)
{
for (int i= 0; i <=MAX_BITS -1 ;)
{
/* if(i %2 ==0) JUST TO SWAP ODD BITS and if(i%2==1) JUST USE FOR EVEN BITS SWAPPING */
/* this is for odd-odd swap */
int bit1    = (n >> i) & 1;
int bit2    = (n >> i+2)& 1;

if(bit1 !=bit2)
n = swap_bits(n,i,i+2);

/* This is for even-even swap */
int j=i+1;
bit1    = (n >> j) & 1;
bit2    = (n >> j+2)& 1;

if(bit1 !=bit2)
n = swap_bits(n,j,j+2);

i=i+4;
}

return n;
}

int main()
{
int n = 22;
printf("\n The result after swapping is: %d",swap_odd_odd_even_even(n));
return 0;
} ``````

Output:

``The result after swapping is: 73``

Categories: C Language