位运算常用技巧
package test;
public class Test {
public static void main(String[] args) {
//清零 将高位低位都置0 直接赋值0不就完了?
print(0b00001010&0b00000000);//X&0 = 0
//不变
print(0b00001010&0b11111111);//00001010
//取低4位,将高4位置0
print(0b10110011&0b00001111);//0000 0011
//取高4位,将低4位置0
print(0b10110001&0b11110000);//1011 0000
//========================================================
//都变1
print(0b10011101|0b11111111);//1111 1111 (255)
//不变
print(0b10011101|0b00000000);//1001 1101
//将高4位置1,低4位不变
print(0b10011101|0b11110000);//1111 1101
//将低4位置1,高4位不变
print(0b10011101|0b00001111);//1001 1111
//==========================================================
//取反 电脑补码 64位
print(~0b00001111);//1111 0000
//左移乘,右移除
//整体左移移n位,高位补0
print(32<<0);//0010 0000 乘以2的0次方
print(32<<1);//0100 0000 乘以2的1次方 = 64
print(32<<2);//1000 0000 128
//整体右移n位,高位补0
print(16>>0);//0001 0000 除以 2的0次方 = 16
print(16>>1);//0000 1000 8
print(16>>2);//0000 0100 4
print(16>>3);//0000 0010 2
print(16>>4);//0000 0001 1
print(16>>5);
print(16>>6);
//==========================================================
//异或
int a = 15;
//s = x ^ n ,n <= x,==> s = x - n
print(a^0);//15 不变
print(a^1);
print(a^2);
print(a^3);
print(a^5);
print(a^6);
print(a^7);
print(a^8);
print(a^9);
print(a^10);
print(a^11);
print(a^12);
print(a^13);
print(a^14);
print(a^15);//0
print(a^16);//31 突然变为2n+1 ,然后再递减
print(a^17);
print(a^18);
// 低4位取反
print(0b10101110^0b00001111);//1010 0001
// 高4位取反
print(0b10101110^0b11110000);//0101 1110
//下面的两个计算等价
print(~0b10101110&0b11111111);
print(0b10101110^0b11111111);//0101 0001
//下面的3个计算等价,都不变
print(0b10101110&0b11111111);
print(0b10101110|0b00000000);
print(0b10101110^0b00000000);
}
public static void print(int out){
System.out.println(Integer.toBinaryString(out) +"->"+out);
}
}