Java中的按位操作——Java编程思想笔记
欢迎转载,转载请务必注明出处: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
11113、接下来是按位异或
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按位异或有一个有意思的用法,它可以不用第三方变量,交换两数的值,如下
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函数
    void 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://www.cnblogs.com/read-the-spring-and-autumn-annals-in-night/

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号