Java中的按位操作——Java程式設計思想筆記

夜讀春秋發表於2014-10-25

歡迎轉載,轉載請務必註明出處: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函式

    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





相關文章