按位與(&)和按位或(|)

/**
 * 按位與 : &
 * 按位或 : |
 */
public class Demo {

    /**
     * 按位與: 爲何(5 & 9)的值等於1
     * 按位或: 爲何(5 | 9)的值等於13
     */
    @Test
    public void test() {
        System.out.println(5 & 9); // 1
        System.out.println(5 | 9); // 13

        System.out.println(Integer.toBinaryString(5)); // 0101
        System.out.println(Integer.toBinaryString(9)); // 1001

        /*
         5的二進制數據:0101
         9的二進制數據:1001
         
            1)與操做&:從左向右,上下數字比較,兩個都是1,相同位才賦值爲1
                0101
                1001
                -----
                0001
         
                得出結果:0001(二進制數據),轉爲十進制後的值爲1
                  
            2)或操做|:從左向右,上下數字比較,有一個是1,相同位就賦值爲1
                0101
                1001
                -----
                1101
                
                得出結果:1101(二進制數據),轉爲十進制後的值爲13
         */
    }

    /**
     * 按位與(&)、按位或(|)的使用場景
     */
    @Test
    public void test1() {
        // 配合數字1,2,4,8..進行使用

        // 假設有5個類別
        int type1 = 1;
        int type2 = 2;
        int type3 = 4;
        int type4 = 8;
        int type5 = 16;

        // 裝入type1,type2,type3,type5
        int types = type1 | type2 | type3 | type5; // 未裝入type4

        System.out.println(types); // 23

        // 判斷集合中是否有某個類別
        System.out.println((types & type1) == type1); // true

        System.out.println((types & type2) == type2); // true

        System.out.println((types & type3) == type3); // true

        System.out.println((types & type4) == type4); // false

        System.out.println((types & type5) == type5); // true
    }

}
相關文章
相關標籤/搜索