   # How to swap the two consecutive bits of unsigned integer ?

288 views
How to swap the two consecutive bits of unsigned integer ? posted Nov 4, 2013
swap is needed only if nth and nth bit are different ie 01 or 10.
int main()
{
scanf("%u",&N);
scanf("%u",&k);
/* 1's in bit 0 and bit 1 position */
/* 1's in positions k and k+1 and 0's else where */
/* 0's in positions k and k+1 and 1's else where */
/* bring bits at position k and k+1 to bit 0 and bit 1 position*/
if(T1!=0&&T1!=3)
{
T1=T1<<k; /* shift the swapped bits to original position*/
/* append other bits(0 to k-1 and k+2 to 15) */
T3=T2|T1;
printf("%u",T3);
}
else
printf("%u",N);
}
unsigned char t1,t2;
t1=c&0*0F;
t2=c&0*F0;
t1=t1<<4;
t2=t2>>4;
return (t2|t1);

+1 vote

Try this to swap all consecutive bits

For 8 bit integer

``````u_int8 swap_bits(u_int8 ch)
{
return ((ch & 0xAA)>>;1 ) | ( (ch & 0x55) << 1);
}
``````

For 16 bit integer

``````u_int16 swap_bits(u_int16 ch)
{
return ((ch & 0xAAAA)>>;1 ) | ( (ch & 0x5555) << 1);
}
`````` answer Nov 5, 2013 by anonymous
Similar Questions