欢迎转载,转载请务必注明出处:http://blog.csdn.net/alading2009/article/details/40450421
Java中的按位操作符有四个,分别是:&(按位与)、|(按位或)、^(按位异或)、~(按位非)。
1、先来看按位与(&)
public class Main {
public static void main(String[] args) {
//按位与,两1得1,遇0得0
System.out.println(Integer.toBinaryString(13));
System.out.println(Integer.toBinaryString(11));
System.out.println(Integer.toBinaryString(13&11));
}
}结果为:
1101 1011 1001
从结果可以清晰的看到,与的规则为:两位相与,若有一位为0,则结果为0,否则为1。
2、然后是按位或(|)
<span style="font-size:18px;">public class Main {
public static void main(String[] args) {
//按位或,两0得0,遇1得1
System.out.println(Integer.toBinaryString(13));
System.out.println(Integer.toBinaryString(11));
System.out.println(Integer.toBinaryString(13|11));
}
}</span>结果为:
1101 1011 1111这样就得到了按位或的结果
3、接下来是按位异或
public class Main {
public static void main(String[] args) {
//按位异或:两位不同得1,两位相同得0
System.out.println(Integer.toBinaryString(13));
System.out.println(Integer.toBinaryString(11));
System.out.println("0"+Integer.toBinaryString(13^11));
}
}
结果为:
1101 1011 0110不同得1,相同得0
按位异或有一个有意思的用法,它可以不用第三方变量,交换两数的值,如下
public class Main {
public static void main(String[] args) {
//使用按位异或交换两数的值
int temp1=10;
int temp2=114;
System.out.println("交换前:temp1:"+temp1);
System.out.println("交换前:temp2:"+temp2);
temp1^=temp2;
temp2^=temp1;
temp1^=temp2;
System.out.println("交换后:temp1:"+temp1);
System.out.println("交换后:temp2:"+temp2);
}
}结果为:
交换前:temp1:10 交换前:temp2:114 交换后:temp1:114 交换后:temp2:10这个是有依据的,这样来看,
第一步:temp1^=temp2,即temp1=temp1^temp2
第二步:temp2=temp2^temp1=temp2^(temp1^temp2),异或满足交换律,去括号后最后得到temp2=temp1
第三步:temp1=temp1^temp2=(temp1^temp2)^temp2=temp1^temp2^temp1=temp2
经过这三步,顺利交换了两变量的值。
这个方法告诉我们,可以在C++中这样实现swap函数
int swap(int &a, int &b){
a^=b;
b^=a;
a^=b;
}这里使用了传引用,当然你也可以用传指针的方式实现
4、最后是按位非(~)
public class Main {
public static void main(String[] args) {
//按位非:逐位取反
System.out.println("0000000000000000000000000000"+Integer.toBinaryString(13));
System.out.println(Integer.toBinaryString(~13));
}
}
结果为:
00000000000000000000000000001101 11111111111111111111111111110010
欢迎转载,转载请务必注明出处:http://blog.csdn.net/alading2009/article/details/40450421
原文地址:http://blog.csdn.net/alading2009/article/details/40450421