位运算是对整数的二进制位进行相关操作,详细运算如下:
A | ~A |
1 | 0 |
0 |
1 |
A | B | A&B |
1 | 1 | 1 |
1 | 0 | 0 |
0 | 1 | 0 |
0 | 0 | 0 |
A | B | A | B |
1 | 1 | 1 |
1 | 0 | 1 |
0 | 1 | 1 |
0 | 0 | 0 |
A | B | A&B |
1 | 1 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
0 | 0 | 0 |
示例如下:
/**
* 位运算
* @author sun
*
*/
public class Bitoperation {
public static void main(String[] args) {
int a = 15;
int b = 2;
System.out.println(a + "&" + b + "=" + (a & b));
System.out.println(a + "|" + b + "=" + (a | b));
System.out.println(a + "^" + b + "=" + (a ^ b));
}
}
运算结果如下:
15&2=2
15|2=15
15^2=13
程序分析:
a | 1 | 1 | 1 | 1 | 15 |
b | 0 | 0 | 1 | 0 | 2 |
a&b | 0 | 0 | 1 | 0 | 2 |
a|b | 1 | 1 | 1 | 1 | 15 |
a^b | 1 | 1 | 0 | 1 | 13 |