Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap two bits in given integer

I saw a some solutions but its look complex.

What are the most effective way to swap between two bits in n,m postions?

int swapBits(int num, int nPostion, int mPosition);
like image 376
I.Mac Avatar asked May 02 '26 04:05

I.Mac


2 Answers

Given integer n in which we wants to swap bit at location p1 and p2 : Algorithm : if both bits are same then just return same value else toggle both bits using XOR.

unsigned int swapBits(unsigned int n, unsigned int p1, unsigned int p2)
{
  return (((n >> p1) & 1) == ((n >> p2) & 1) ? n : ((n ^ (1 << p2)) ^ (1 << p1)));
}
like image 99
Parth Bera Avatar answered May 04 '26 16:05

Parth Bera


Not sure it is the most effective, but I think this is a rather simple solution:

int bitValue(int num, int nPosition)
{
    return ( num >> nPosition ) % 2;
}

int swapBits(int num, int nPosition, int mPosition)
{
    int nVal = bitValue(num, nPosition);
    int mVal = bitValue(num, mPosition);

    if (nVal != mVal)
    {
        if (1 == nVal)
        {
           num -= 1<<nPosition;
           num += 1<<mPosition;
        }
        else
        {
            num += 1<<nPosition;
            num -= 1<<mPosition;
        }
    }

    return num;
}

Same solution in a more efficient (but less readable) way:

int swapBits2(int num, int nPosition, int mPosition)
{
    int nVal = ( num >> nPosition ) % 2;
    int mVal = ( num >> mPosition ) % 2;

    if (nVal != mVal)
    {
        num += (-1)*(2*mVal-1)*(1<<mPosition) + (-1)*(2*nVal-1)*(1<<nPosition);
    }

    return num;
}

and last:

int swapBits3(int num, int nPosition, int mPosition)
{
    int k = ((num >> nPosition) & 1) - (num >> mPosition) & 1;

    return num + k*(1<<mPosition) - k*(1<<nPosition);
}
like image 20
Shay Gold Avatar answered May 04 '26 16:05

Shay Gold