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);
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)));
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With