http://www.careercup.com/question?id=1941662
0
of
0 votes
#include<stdio.h>
main()
{
int n, i, j, s;
printf("enter values of n, i and j");
scanf("%d%d%d",&n,&i,&j);
s = swap(n,i,j);
printf("%d",s);
}
swap(int n,int i,int j)
{
if(i!=j)
{
n^= 1<<i;
n^= 1<<j;
}
return n;
}
0
of
0 votes
I'm not sure it's necessary to check for i != j. It would still be correct if i == j; you don't need to incur the cost of a branch.
0
of
0 votes
{
void swap(int&n, int i, int j) {
int xori = (((1 << i) & n ) >> i ) ^ (((1 << j) & n ) >> j );
n ^= xori << i;
n ^= xori << j;
}
}
1
of
1vote
Swapping individual bits with XOR
unsigned int i, j; // positions of bit sequences to swap
unsigned int n; // number of consecutive bits in each sequence
unsigned int b; // bits to swap reside in b
unsigned int r; // bit-swapped result goes here
unsigned int x = ((b >> i) ^ (b >> j)) & ((1U << n) - 1); // XOR temporary
r = b ^ ((x << i) | (x << j));
swap(int n,int i,int j)
- Anonymous 5 years ago | FlagReply{
if( (n & 1<<i)>>i ^ (n & (i<<j))>>j) ) // if bits i and j are different
{
n^= 1<<i;
n^= 1<<j;
}
return n;
}