运算符:位运算
运算符 | 运算 | 范例 |
---|---|---|
<< | 左移 | 3 << 2 = 12 --> 322=12 |
>> | 右移 | 3 >> 1 = 1 --> 3/2=1 |
>>> | 无符号右移 | 3 >>> 1 = 1 --> 3/2=1 |
& | 与运算 | 6 & 3 = 2 |
| | 或运算 | 6 | 3 = 7 |
^ | 异或运算 | 6 ^ 3 = 5 |
~ | 取反运算 | ~6 = -7 |
位运算是直接对整数的二进制进行的运算
注意:无 <<<
总结
- 位运算符操作的都是整型的数据
- << : 在一定范围内,每向左移1位,相等于 * 2;
>> : 在一定范围内,每向左移1位,相等于 / 2;
class BitTest{
public static void main(String[] args){
int i = 21;
System.out.println("i << 2 :" + (i << 2)); //84
System.out.println("i << 3 :" + (i << 3)); //168
System.out.println("i << 27 :" + (i << 27)); //-1476395008
i = -21;
System.out.println("i << 2 : " + (i << 2)); //i << 2 : -84
System.out.println("i << 3 : " + (i << 3)); //i << 3 : -168
System.out.println("i << 27 : " + (i << 27)); //i << 27 : 1476395008
int m = 12;
int n = 5;
System.out.println("m & n : "+ (m & n)); //m & n : 4
System.out.println("m | n : "+ (m | n)); //m | n : 13
System.out.println("m ^ n : "+ (m ^ n)); //m ^ n : 9
//练习: 交换两个变量的值
int num1 = 10;
int num2 = 20;
System.out.println("num1 = " + num1 + ", num2 = " + num2); //num1 = 10, num2 = 20
//方式一: 定义临时变量的方式
//int temp = num1;
//num1 = num2;
//num2 = temp;
//System.out.println("num1 = " + num1 + ", num2 = " + num2); //num1 = 20, num2 = 10
//方式二:
//好处: 不用定义临时变量
//弊端:1.相加操作可能超出存储范围;2.有局限性:只能适用于数值类型
//num1 = num1 + num2;
//num2 = num1 - num2;
//num1 = num1 - num2;
//System.out.println("num1 = " + num1 + ", num2 = " + num2); //num1 = 20, num2 = 10
//方式三:使用位运算
num1 = num1 ^ num2;
num2 = num1 ^ num2;
num1 = num1 ^ num2;
System.out.println("num1 = " + num1 + ", num2 = " + num2); //num1 = 20, num2 = 10
}
}