top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

How to swap the two consecutive bits of unsigned integer ?

+4 votes
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 Google+ Share Button LinkedIn Share Button Multiple Social 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;
  /* 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*/
    T1=T1^Mask1; /* swap */
    T1=T1<<k; /* shift the swapped bits to original position*/
    /* append other bits(0 to k-1 and k+2 to 15) */
unsigned char t1,t2;
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.

Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.