java 中的按位逻辑运算符

bitwise logical operators in java

我正在尝试反转 a 但出了点问题。

String binary[]={
        "0000","0001","0010","0011","0100","0101",
        "0110","0111","1000","1001","1010","1100",
        "1101","1110","1111"
    };
    int a=3;
    int b=6;
    int c=a|b;
    int d=a&b;
    int e=a^b;
    int f=(~a &b) | (a&~b);
    int g= ~a & 0x0f;

    System.out.println(" a="+binary[a]);
    System.out.println(" b="+binary[b]);
    System.out.println(" a|b="+binary[c]);
    System.out.println(" a&b="+binary[d]);
    System.out.println(" a^b="+binary[e]);
    System.out.println(" ~a&b|a&~b="+binary[f]);
    System.out.println(" ~a="+binary[g]);**

输入是:

 a=0011
 b=0110
 a|b=0111
 a&b=0010
 a^b=0101
 ~a&b|a&~b=0101
 ~a=1101

最后一个是wrong.a的反转一定是1100.What我做错了吗?

String binary[]={
    "0000","0001","0010","0011",
    "0100","0101","0110","0111",
    "1000","1001","1010","1011",
    "1100","1101","1110","1111"
};

初级:你错过了一个二进制值。以更明显的模式排序会有所帮助。

你的二进制字符串不正确,位移是正确的,这是正确的二进制字符串数组:

String binary[]={
            "0000","0001","0010","0011","0100","0101",
            "0110","0111","1000","1001","1010","1011",
            "1100","1101","1110", "1111"
    };

你的代码输出如下:

a=0011
b=0110
a|b=0111
a&b=0010
a^b=0101
~a&b|a&~b=0101
~a=1100