Given an 32-bit integer X, swap the i-th and j-th bit.

http://www.careercup.com/question?id=1941662


swap(int n,int i,int j) 

if( (n & 1<<i)>>i ^ (n & (i<<j))>>j) ) // if bits i and j are different 

n^= 1<<i; 
n^= 1<<j; 

return n; 
}

- Anonymous 5 years ago FlagReply
0
of  0 votes

excellent! thanks,

- Anonymous 5 years ago Flag
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; 
}

- V: 5 years ago Flag
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.

- Bullocks 5 years ago Flag
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; 

}

- Anonymous 5 years ago Flag
0
of  0 votes

void swap(int&n, int i, int j) {
    n ^= !((1<<i)&n)^!((1<<j)&n);
}

- Bullocks 4 years ago Flag
0
of  0 votes

My bad. That was incorrect. Please ignore the last comment.

- Bullocks 4 years ago Flag
0
of  0 votes

I do not understand how this solution works out. 
let n = 01'1'1 01'1'0 
i = 6,j=2 ( quoted those two bit positions - bit position starting from 1 from left end). 

n^=(1<<i) 
1<<6 => 0100 0000 
n = n^(1<<6) = 0011 0110 

n=n^(1<<j) = n^(1<<2) 
1<<2 => 0000 0100 
n = n^(1<<2) = 0011 0010

- Krishna 2 years ago Flag
0
of  0 votes

little addition of simplicity 

int temp = ((n & (1 <<i)) | (n & (1 <<j))) 
if (temp & temp-1==0) //bits are different 

n^=1<<i; 
n^=1<<j; 
}

- Manju 2 years ago Flag
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));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值