位运算:
~(非)——》二进制数进行0和1的互换

样例:

public class Test {
	public static void main(String[] args) {
		System.out.println(~-2);//输出1
		System.out.println(~-1);//输出0
		System.out.println(~0);//输出-1
		System.out.println(~1);//输出-2
		System.out.println(~2);//输出-3
		System.out.println(~3);//输出-4
	}
}






^(异或)——》12 ^ 10 = ...01100^01010 =  00110 = 6

样例:

public class Test {
	public static void main(String[] args) {
		int a = 0;
		int b = 0;
		b = a = 12^10;
		System.out.println(a);//输出为 6
		a = a^12;
		System.out.println(a);//输出为 10
		b = b^10;
		System.out.println(b);//输出为 12
	}
}


应用:二个不同的数进行交换

public class Test {
	public static void main(String[] args) {
		int a = 12;
		int b = 10;
		System.out.println(a + "---" + b);// 输出为12---10
		a = a ^ b;
		b = a ^ b;
		a = a ^ b;
		System.out.println(a + "---" + b);// 输出为10---12
	}
}



&(与)——》12 & 10 = ...01100 & 01010 = 01000 = 8

样例:

public class Test {
	public static void main(String[] args) {
		int a = 12;
		int b = 10;
		int c = a&b;
		System.out.println(c);//输出为 8
	}
}


应用:

public class Test {
	public static void main(String[] args) {
		int[] a = new int[2];
		a[0] = 5;
		a[1] = 6;
		for (int i = 0; i < a.length; i++) {
			if ((a[i] & 1) == 1) {// 推断是否为奇数
				System.out.println(a[i] + "奇数");
			} else {
				System.out.println(a[i] + "偶数");
			}
		}
		// 输出为:
		// 5"奇数"
		// 6"偶数"
	}
}


|(或)——》12 | 10 = ...01100 | ...01010 = 01110 = 14

样例:

public class Test {
	public static void main(String[] args) {
		int a = 12;
		int b = 10;
		// ...01100 | ...01010 = 01110 = 14
		int c = a | b;
		System.out.println(c);// 输出为14
	}
}


应用:和位移一起运算能够打包成不同位数的整数

public class Test {
	public static void main(String[] args) {
		int a = 1;
		int b = 2;
		// 256 | 2 = ...01 0000 0000 | ...0010 = ...01 0000 0010 = 258
		int c = a << 8 | b;
		System.out.println(c);// 输出为258
	}
}


>>(右位移)——》12>>2 = 00...01100 >>2 = 00...00011 = 3

-1 >>>24 = 1111...111 >>>24 = 1111...1111 1111 = -1
>>>(无符号)——》 -1 >>> 24 = 1111...111 >>> 24 = 0000...1111 1111 = 255

public class Test {
	public static void main(String[] args) {
		int a = -1;
		// 1111...111 >>> 24 = 0000...1111 1111 = 255
		int b = a>>>24;
		System.out.println(b);// 输出为255
	}
}
12>>2 = 00...01100 >>2 = 00...00011 = 3