符号:
&与 |或 ^异或
<<左移 >>右移
>>>无符号位右移
注意:
&、|、^前后两侧都是数值,此符号为位运算符
&、|、^前后两侧都是布尔值,此符号为逻辑运算符
&与:同位比较,两者为1,结果才为1
byte b1 = 19;//0001,0011 byte b2 = 21;//0001,0101 //b1 - byte:0001,0011 // int:0000,0000,0000,0000,0000,0000,0001,0011 //b2 - byte:0001,0101 // int:0000,0000,0000,0000,0000,0000,0001,0101 // 结果:0000,0000,0000,0000,0000,0000,0001,0001 // (byte):0001,0001 byte result = (byte)(b1 & b2); System.out.println(result);//17
|或:同位比较,两者有1,结果就为1
int i1 = 19;//0000,0000,0000,0000,0000,0000,0001,0011 int i2 = 21;//0000,0000,0000,0000,0000,0000,0001,0101 //0000,0000,0000,0000,0000,0000,0001,0111 int result = i1 | i2; System.out.println(result);//23
^异或:同位比较,两者相同为0,不同为1
int i1 = 19;//0000,0000,0000,0000,0000,0000,0001,0011 int i2 = 21;//0000,0000,0000,0000,0000,0000,0001,0101 //0000,0000,0000,0000,0000,0000,0000,0110 int result = i1 ^ i2; System.out.println(result);//6
<<左移:整体向左移动n位,就用n个0补位(补到最低位)
经验:左移1位相等于乘以2int a = 1024;//0000,0000,0000,0000,0000,0100,0000,0000 System.out.println(a << 2);//4096 -- 0000,0000,0000,0000,0001,0000,0000,0000
思考题:左移是否会出现负数?
会
int b = 1024;//0000,0000,0000,0000,0000,0100,0000,0000 System.out.println(b << 21);//-2147483648:1000,0000,0000,0000,0000,0000,0000,0000
>>右移:整体向右移动n位,就用n个最高位补位(补到最高位,负数用1补位,正数用0补位)
注意:右移1位相等于除以2int c = 1024;//0000,0000,0000,0000,0000,0100,0000,0000 System.out.println(c >> 2);//256 -- 0000,0000,0000,0000,0000,0001,0000,0000 int d = -1024;//1111,1111,1111,1111,1111,1100,0000,0000 System.out.println(d >> 2);//-256 -- 1111,1111,1111,1111,1111,1111,0000,0000
>>>无符号位右移:整体向右移动n位,就用n个0补位(补到最高位)
注意:右移和无符号位右移在处理正数的情况下都是一样的,因为正数用0补位
int e = 1024;//0000,0000,0000,0000,0000,0100,0000,0000 System.out.println(e >>> 2);//256 -- 0000,0000,0000,0000,0000,0001,0000,0000 int f = -1024;//1111,1111,1111,1111,1111,1100,0000,0000 System.out.println(f >>> 2);//1073741568 -- 0011,1111,1111,1111,1111,1111,0000,0000