java运算符(与,或,非,异或)

public class test{

    // 与运算符用符号“&”表示
    // 只有两个位都是1,结果才是1,可以知道结果就是1,即1
    public static void main(String[] args) {
        int a = 1;
        int b = 129;
        System.out.println(a + " toBinary :" + Integer.toBinaryString(a));
        System.out.println(b + " toBinary :" + Integer.toBinaryString(b));
        System.out.println(a + " & " + b + " = " + (a & b));
    }

}

output :

1 toBinary :1
129 toBinary :10000001
1 & 129 = 1


public class test{

    // 或运算符用符号“|”表示
    // 两个位只要有一个为1,那么结果就是1,否则就为0,可以知道结果就是10000001,即129
    public static void main(String[] args) {
        int a = 1;
        int b = 129;
        System.out.println(a + " toBinary :" + Integer.toBinaryString(a));
        System.out.println(b + " toBinary :" + Integer.toBinaryString(b));
        System.out.println(a + " | " + b + " = " + (a | b));
    }
}

output :

1 toBinary :1
129 toBinary :10000001
1 | 129 = 129


public class test{

    // 或运算符用符号“~”表示
    public static void main(String[] args) {
        int b = 129;
        System.out.println(b + " toBinary :" + Integer.toBinaryString(b));
        System.out.println(~b);
    }
}

output :

129 toBinary :10000001
-130


public class test{

    // 或运算符用符号“^”表示
    // 两个操作数的位中,相同则结果为0,不同则结果为1,可以知道结果就是10000000,即128
    public static void main(String[] args) {
        int a = 1;
        int b = 129;
        System.out.println(a + " toBinary :" + Integer.toBinaryString(a));
        System.out.println(b + " toBinary :" + Integer.toBinaryString(b));
        System.out.println(a + " ^ " + b + " = " + (a ^ b));
    }
}

output :

1 toBinary :1
129 toBinary :10000001
1 ^ 129 = 128


你可能感兴趣的:(JAVA基础)