Java位运算
位与运算(&)
只有1&1,结果才能是1,其余情况均为0
0 | 0 | 0 |
---|---|---|
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
例子
public class Example{
public static void main(String args[]) {
System.out.println(2 & 10);
}
}
//结果为2=> 0010 & 1010 = 0010 = 2
位或运算(|)
只有0|0,结果是0,其余情况均为1
0 | 0 | 0 |
---|---|---|
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
例子
public class Example{
public static void main(String args[]) {
System.out.println(2 | 10);
}
}
//结果为10 => 0010 | 1010 = 1010 = 10
异或运算(|)
相同为0,不同为1
0 | 0 | 0 |
---|---|---|
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
例子
public class Example{
public static void main(String args[]) {
System.out.println(2 ^ 10);
}
}
//结果为8 => 0010 ^ 1010 = 1000 = 8
非运算(~)
取反
例子
public class Example{
public static void main(String args[]) {
System.out.println(~2);
}
}
//结果为-3 => ~2 = ~00000000 00000000 00000000 00000010 = 11111111 11111111 11111111 11111101 = -3(-3在计算机中补码表示, 负数的补码 通过 符号为不变,其余取反, 最后加一 可以得到)
左移(<<)
所有位左移一位,低位补0. 左移一位,相当于乘以2,以此类推
public class Example{
public static void main(String args[]) {
System.out.println(10 << 1);
}
}
//结果为20 = 10 << 1 = 00001010 << 1 = 00010100 = 20
右移(>>)
所有位右移一位,高位补0. 右移一位,相当于除以2(整除),以此类推
public class Example{
public static void main(String args[]) {
System.out.println(10 >> 1);
}
}
//结果为5 = 10 >> 1 = 1010 >> 1 = 0101 = 5
位移特殊情况
public class Example{
public static void main(String args[]) {
System.out.println(-2147483648 << 1);
}
}
//结果为 0.
//-2147483648 << 1 = 10000000000000000000000000000000 << 1
//= 00000000000000000000000000000000 = 0
来源:CSDN
作者:zycxnanwang
链接:https://blog.csdn.net/zycxnanwang/article/details/103833127