Monday, 8 December 2014

C program to reverse bits of an integer

program to reverse bits of an integer
#include<stdio.h>
main()
{
int n,i,j,m,k;
printf("enter n value\n");
scanf("%d",&n);
printf("n=%d\n",n);
for(i=31;i>=0;i--)
printf("%d",(n>>i)&1?1:0);
printf("\n");
for(i=31,j=0;i>j;i--,j++)
{
m=(n>>i)&1;
k=(n>>j)&1;
if(m^k)
{
n=n^(1<<i);
n=n^(1<<j);
}
}
printf("n=%d\n",n);
for(i=31;i>=0;i--)
printf("%d",(n>>i)&1?1:0);
printf("\n");
}
OutPut:
madan@madan-Lenovo-G570:~/madan$ cc ex53.c
madan@madan-Lenovo-G570:~/madan$ ./a.out
enter n value
15
n=15
00000000000000000000000000001111
n=-268435456
11110000000000000000000000000000