异或1
奇偶数:十进制转二进制数逐个位数异或的值为零是奇数
private static void isOdd(int a) {
int b = 0;
String binStr = Integer.toBinaryString(a);
for (int x = 0, len = binStr.length() - 1; x < len; x++) {
b = b ^ (binStr.charAt(x) ^ binStr.charAt(x + 1));
}
System.out.println(a + " > 二进制: " + binStr);
System.out.println(a + "=" + (b == 0 ? "奇数" : "偶数"));
}
=========
isOdd(10)
异或2
两整数交换
int a = 10, b = 9;
a ^= b;
b ^= a;
a ^= b;
System.out.println("a:" + a + ", b:" + b);
异或3
任意一个数异或零都为它本身
int c = 100;
c ^= 0;
System.out.println("c:" + c);
位移运算
左位移 = 乘以2的n次幂,右位移 = 除以2的n次幂:
8 << 3(n) = 64, 8 >> 3(n) = 1
System.out.println("===>> " + (8*(2 * 2 * 2)) + ", " + (8 << 3));
System.out.println("===>> " + (8 / (2 * 2 * 2)) + ", " + (8 >> 3));
与运算
取模,n-1相与:9 % 4(n) = 9 & (4 - 1) = 1
System.out.println((9 % 4) + ", " + (9 & 3));
附:为什么HashMap的容量总是2的n幂次方