public static void main(String[] args) {
/*
* &:与运算
* 全为1则为1,否则为0
*/
System.out.print(1 & 0);
System.out.print("--");
System.out.print(1 & 1);
System.out.print("--");
System.out.println(0 & 0);
// out:0--1--0 /*
* |:或运算
* 全为0则为0,否则为1
*/
System.out.print(1 | 0);
System.out.print("--");
System.out.print(1 | 1);
System.out.print("--");
System.out.println(0 | 0);
// out:1--1--0 /*
* ^:异或运算
* 相同为0,不同为1
*/
System.out.print(1 ^ 0);
System.out.print("--");
System.out.print(1 ^ 1);
System.out.print("--");
System.out.println(0 ^ 0);
// out:1--0--0
}

关于'<<'与'>>'操作:

  • m<<n,表示m二进制,右边尾部加0;
  • m>>n,表示m二进制,右边尾部去掉1位;
  • m>>>n,表示m二进制,忽略其符号位,从左至右,去掉最后的n位;
  • 不存在'<<<';
 public static void main(String[] args) {
int integer = 2;
printBinary(integer);
integer = 2 >> 1;
printBinary(integer);
integer = 2 >> 2;
printBinary(integer);
integer = 2 >> 3;
printBinary(integer);
System.out.println("====================");
integer = 2 << 1;
printBinary(integer);
integer = 2 << 2;
printBinary(integer);
integer = 2 << 3;
printBinary(integer);
System.out.println("====================");
integer = -2 << 1;
printBinary(integer);
System.out.println("====================");
integer = -2 >> 1;
printBinary(integer);
System.out.println("====================");
integer = 3 >> 1;
printBinary(integer);
System.out.println("====================");
integer = -2;
printBinary(integer);
printBinary(integer>>>1);
printBinary(-integer);
printBinary(-integer>>>1);
}
private static void printBinary(Integer integer) {
System.out.println("Integer.toBinaryString()="+Integer.toBinaryString(integer)+", integer="+integer);
}
/**
Integer.toBinaryString()=10, integer=2
Integer.toBinaryString()=1, integer=1
Integer.toBinaryString()=0, integer=0
Integer.toBinaryString()=0, integer=0
====================
Integer.toBinaryString()=100, integer=4
Integer.toBinaryString()=1000, integer=8
Integer.toBinaryString()=10000, integer=16
====================
Integer.toBinaryString()=11111111111111111111111111111100, integer=-4
====================
Integer.toBinaryString()=11111111111111111111111111111111, integer=-1
====================
Integer.toBinaryString()=1, integer=1
====================
Integer.toBinaryString()=11111111111111111111111111111110, integer=-2
Integer.toBinaryString()=1111111111111111111111111111111, integer=2147483647
Integer.toBinaryString()=10, integer=2
Integer.toBinaryString()=1, integer=1
*/
05-08 08:22