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

Facebook Login
Site Registration

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

+4 votes
561 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 Google+ Share Button LinkedIn Share Button Multiple Social 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
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...