java中有7个位运算(&、|、^、~、>>、<<和>>>)
&、|、^、~的运算规则如下图:
演示如下:
//位运算
public class BitOperator {
//编写一个main方法
public static void main(String[] args) {
//看推导过程
//1. 先得到 2的补码 => 2的原码 00000000 00000000 00000000 00000010
// 2的补码 00000000 00000000 00000000 00000010
//2. 3的补码 3的原码 00000000 00000000 00000000 00000011
// 3的补码 00000000 00000000 00000000 00000011
//3. 按位&
// 00000000 00000000 00000000 00000010
// 00000000 00000000 00000000 00000011
// 00000000 00000000 00000000 00000010 & 运算后的补码
// 运算后的原码 也是 00000000 00000000 00000000 00000010
// 结果就是 2
System.out.println(2&3);//2
//推导
//1. 先得到 -2的原码 10000000 00000000 00000000 00000010
//2. -2的 反码 11111111 11111111 11111111 11111101
//3. -2的 补码 11111111 11111111 11111111 11111110
//4. ~-2操作 00000000 00000000 00000000 00000001运算后的补码
//5. 运算后的原码 就是 00000000 00000000 00000000 00000001 => 1
System.out.println(~-2);//1
//推导
//1. 得到2的补码 00000000 00000000 00000000 00000010
//2. ~2操作 11111111 11111111 11111111 11111101 运算后的补码
//3. 运算后的反码 11111111 11111111 11111111 11111100
//4. 运算后的原码 10000000 00000000 00000000 00000011=>-3
System.out.println(~2); //-3
}
}
还有3个位运算符>>、<<和>>>,运算规则:
1)算术右移>>:低位溢出,符号位不变,并用符号位补溢出的高位
2)算术左移<<:符号位不变,低位补
03)>>>逻辑右移也叫无符号右移,运算规则是:低位溢出,高位补
04)特别说明:没有<<<符号
演示如下:
public class BitOperator02 {
//编写一个main方法
public static void main(String[] args) {
System.out.println(1 >> 2); //0
System.out.println(1 << 2); //4
System.out.println(4 << 3); // 4 * 2 * 2 * 2 = 32
System.out.println(15 >> 2); // 15 / 2 / 2 = 3
System.out.println(-10.4%3); // -1.4近似值
int i=66;
System.out.println(++i+i); //134
}
}