/* 位运算符: <<: 左移 >>:右移 >>>:无符号右移 &:按位与 |:按位或 ^:按位异或 a ^ a = 0 a ^ 0 = a a ^ b = b ^ a a ^ b ^ c = a ^ (b ^ c) ~:按位取反, 单目运算符 问题:位运算能操作哪些基本类型的数据? 只能操作整数类型 (char可以看成无符号的整数) 注意事项: 位运算是运算效率最高的 ^ 不是幂运算, 而是按位异或. */
classOpereatorDemo1{ publicstaticvoidmain(String[] args){ byte b = 1; short s = 2; int i = 3; long l = 4; float f = 5.0f; double d = 6.0; char c = '中'; boolean flag = false; System.out.println(~b); System.out.println(~s); System.out.println(~i); System.out.println(~l); // System.out.println(~f); // System.out.println(~d); System.out.println(~c); // System.out.println(~flag); } }
/* 怎么求一个数对2^n取余。 int a = 3; int m = 8; System.out.println(3 % 8); */
classOpereatorDemo4{ publicstaticvoidmain(String[] args){ int a = 2019; int m = 8; System.out.println(a % m); System.out.println(a & (m-1)); int n = 11; System.out.println(a % n); System.out.println(a & (n-1)); } }
classOpereatorDemo5{ publicstaticvoidmain(String[] args){ int m = 8; int n = 7; System.out.println((m & m - 1) == 0); System.out.println((n & n - 1) == 0); } }
classOpereatorDemo7{ publicstaticvoidmain(String[] args){ int a = 4; int b = 3; // 方式一 /*System.out.println("a=" + a + ", b=" + b); int temp = a; a = b; b = temp; System.out.println("a=" + a + ", b=" + b);*/ // 方式二: 加法和减法互为逆运算. /*System.out.println("a=" + a + ", b=" + b); a = a + b; // a = 4 + 3, b = 3 b = a - b; // a = 4 + 3, b = 4 a = a - b; // a = 3, b = 4 System.out.println("a=" + a + ", b=" + b);*/ // 方法三: /*System.out.println("a=" + a + ", b=" + b); a = a ^ b; b = b ^ a; a = a ^ b; System.out.println("a=" + a + ", b=" + b);*/ // 方式四 System.out.println("a=" + a + ", b=" + b); // a ^= b ^= a ^= b; // a = a + b - (b = a); // a = 4 + 3 - 4; a = a ^ b ^ (b = a); // a = 4 + 3 - 4; System.out.println("a=" + a + ", b=" + b); } }