位运算总结
1.交换两个数
2.选择两个数中较大的一个
3.位运算进行加减乘除
下面给出代码
//交换两个数
public void swap(int a,int b) {
a = a^b;
b = a^b;
a = a^b;
System.out.println("a: " + a + " , b:" + b);
}
//获取两个数较大的
int getMax(int a,int b) {
int c = a - b;
int sign = (c>>31) & 1;
int flag = sign ^ 1;
return a * flag + b * sign;
}
//加法
int add(int a,int b){
while(b != 0){
int c = a ^ b;
b = (a & b)<<1;
a = c;
}
return a;
}
//减法
int minus(int a,int b){
return add(a,add(~b,1));
}
//乘法
int multiply(int a,int b) {
int res = 0;
while(b!=0){
if((b&1)==1){
res = add(res,a);
}
a <<= 1;
b >>>= 1;
}
return res;
}
//除法
int div(int a,int b){
int signA = (a>>31) & 1;
int signB = (b>>31) & 1;
if (signA == 1){
a = add(~a,1);
}
if (signB == 1) {
b = add(~b,1);
}
int res = 0;
long c = b;
for(int i=30;i>=0;i=minus(i,1)) {
if(a < (c<<i)) continue;
else{
res = add(res,1<<i);
a = minus(a,b<<i);
}
}
if (signA==1) {
res = add(~res,1);
}
if (signB==1) {
res = add(~res,1);
}
return res;
}
public static void main(String[]args) {
BitOper bitOper = new BitOper();
bitOper.swap(1,2);
System.out.println(bitOper.getMax(101,12));
System.out.println(bitOper.add(9999,1));
System.out.println(bitOper.minus(1020,9999));
System.out.println(bitOper.multiply(-11,-2));
System.out.println(bitOper.div(11,3));
}