top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to swap the two consecutive bits of unsigned integer ?

+4 votes
871 views
How to swap the two consecutive bits of unsigned integer ?
posted Nov 4, 2013 by Anuj Yadav

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
swap is needed only if nth and nth bit are different ie 01 or 10.
int main()
{
  unsigned int N,Mask1,Mask2,Mask3,T1,T2,T3,k;
  scanf("%u",&N);
  scanf("%u",&k);
  /* 1's in bit 0 and bit 1 position */
  Mask1=0x0003;
  /* 1's in positions k and k+1 and 0's else where */
  Mask2=Mask1<<k;
  /* 0's in positions k and k+1 and 1's else where */
  Mask3=~Mask2;
  /* bring bits at position k and k+1 to bit 0 and bit 1 position*/
  T1=(N&Mask2)>>k;
  if(T1!=0&&T1!=3)
  {
    T1=T1^Mask1; /* swap */
    T1=T1<<k; /* shift the swapped bits to original position*/
    T2=N&Mask3;
    /* 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 Answer

+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
+6 votes

Write a program to reverse the bits of an unsigned integer ??

+4 votes

How to swap ith and jth Bits for a 32-Bit Integer?

+6 votes

What is the simples way to check if the sum of two unsigned integers has resulted in an overflow.

...