top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Swap the ith and jth Bits for a 32-Bit Integer.

+4 votes
1,174 views

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

posted Nov 23, 2013 by Vikas Upadhyay

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+3 votes

We can also reduce the no of instruction through this

int bit_swap(int num, int i, int j)
{
        return( ( ((n >> i) & 1) == ((n >> j) & 1) ) ? n : (n ^ ( (1<<i) | (1 << j) ) ));
}
answer Nov 23, 2013 by Sachidananda Sahu
+1 vote
int bit_swap(int num, int i,int j)
{
        int m = (num >> i) & 1;         /* TO KNOW THE PARTICULAR DESTINATION BIT */
        int n = (num >> j) & 1;         /* TO KNOW THE PARTICULAR SOURCE BIT */

        if (m != n) {                   /* IF BOTH ARE NOT EQUAL */
                num = num ^ (1 << i);
                num = num ^ (1 << j);
        }
        return num;
}
answer Nov 23, 2013 by Sachidananda Sahu
...