逻辑/位运算
- ^ 异或运算
相同为0,不同为1
public class test{
public static void main (String[] args){
System.out.println("2^3 = "+(2^3));
//0010 ^ 0011 结果为1(0001)
}
}
- & 与运算
相同为1,不同为0
public class test{
public static void main (String[] args){
System.out.println("2&3 = "+(2&3));
//0010 & 0011 结果为2(0010)
}
}
- 左移<< 右移>>
按位左移,右缺0补
按位右移,左缺0补,若带符号,值为负最高位插1,值为正最高位插0,
public class test{
public static void main (String[] args){
System.out.println("16<<3 = "+(16<<3));
//00010000 左移3位结果为128(10000000)
System.out.println("-16>>3 = "+(-16>>3));
//10010000 右移3位结果为-2(10000010)
}
}
- 无符号右移>>>
按位右移,无论正负,最高位插0
public class test{
public static void main (String[] args){
System.out.println("-16>>>3 = "+(-16>>>3));
//-16无符号右移3位结果为536870910
}
}