Thursday, September 12, 2013

Swapping the bits of an integer using c (compile using gcc filename.c -lm)

#include<stdio.h>
#include<math.h>
#include<stdlib.h>


void showbit(int h);

int main()
{   
    int no,temp,temp1;
    double a,b;
   
   
    printf("\nEnter the no.:\t");
    scanf("%d",&no);

    showbit(no);
    printf("\nEnter the bit index :  ");
    scanf("%lf",&a);
    printf("\nEnter the bit index :  ");
    scanf("%lf",&b);
   
    a=pow(2.0,a);
    temp=no&(int)a;
    (temp==0)?(temp=0):(temp=1); //checking whether the specified bit is 0 or 1

    b=pow(2.0,b);
    temp1=no&(int)b;
    (temp1==0)?(temp1=0):(temp1=1);



    if(temp1==temp) // if both the bits are same no need to swap
    {
    showbit(no);
    exit(0);
    }   
    else
    {

    no=no^(int)a; // if bits are different toggle them
    no=no^(int)b;

    }
    showbit(no);
   
    return 0;
}       
   
void showbit(int h) //displaying the bits of a number
{
    int l;
     int i,j,k[32];
    i=1;
    l=h&i;
    (l==0)?(k[0]=0):(k[0]=1);
   
    for(j=1;j<32;j++)
    {
    i*=2;
    l=h&i;
    (l==0)?(k[j]=0):(k[j]=1);
    }
    for(j=31;j>=0;j--)
    printf("%d",k[j]);

    printf("\n");

}

2 comments: