java中二进制字符串的Xor

时间:2013-12-23 14:17:52

标签: java

我使用以下代码来XOR 2字符串

String lseq = "0011111111101111111111111100101101111100110000001011111000010100";
String tseq = "0011111111100000110011001100110011001100110011001100110011001100";

StringBuilder sb = new StringBuilder();

for(int i = 0; i < lseq.length(); i++)
    sb.append((lseq.charAt(i) ^ tseq.charAt(i)));

String result = sb.toString();
System.out.println(result);

上面的代码给出了正确的输出:

0000000000001111001100110000011110110000000011000111001011011000

我需要再多一个字符串

String hseq = "0011111111110010010111110100010111100000101101001110000100011110";

如果我尝试sb.append((lseq.charAt(i) ^ tseq.charAt(i) ^ hseq.charAt(i));

我收到了结果:

48484848484848484848484948484948494848494848494949484848494848494848494849494848484949494948484848484948494948494949484948484948

这是错误的。我需要帮助做3个二进制字符串的xor

3 个答案:

答案 0 :(得分:7)

我会这样做

private static boolean bitOf(char in) {
    return (in == '1');
}

private static char charOf(boolean in) {
    return (in) ? '1' : '0';
}

public static void main(String[] args) {
    String lseq ="0011111111101111111111111100101101111100110000001011111000010100";
    String tseq ="0011111111100000110011001100110011001100110011001100110011001100";
    String hseq ="0011111111110010010111110100010111100000101101001110000100011110";

    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < lseq.length(); i++) {
        sb.append(charOf(bitOf(lseq.charAt(i)) ^ bitOf(tseq.charAt(i))
                ^ bitOf(hseq.charAt(i))));
    }

    String result = sb.toString();
    System.out.println(result);
}

哪个输出

0011111111111101011011000100001001010000101110001001001111000110

答案 1 :(得分:0)

您可以使用BigInteger,它会使您的代码更简单。它有一个构造函数,您可以在其中传递String和要使用的基础(在您的情况下为2)。

然后你可以进行XOR调用public BigInteger xor(BigInteger val)(请参阅docs或查看openjdk BigInteger's code

答案 2 :(得分:0)

您还可以考虑以下内容:

String lseq = "0011111111101111111111111100101101111100110000001011111000010100";
String tseq = "0011111111100000110011001100110011001100110011001100110011001100";
String hseq = "0011111111110010010111110100010111100000101101001110000100011110";

StringBuilder sb = new StringBuilder();

for(int i = 0; i < lseq.length(); i++)
    sb.append((lseq.charAt(i) - '0' ^ tseq.charAt(i) - '0' ^ hseq.charAt(i) - '0'));

String result = sb.toString();
System.out.println(result);

在引擎盖下,char被视为int,因为数值代表预定义的字符。我们可以从字符中减去字符“ 0”的值(知道“ 1”的值仅比“ 0”多1),然后得到0或1,可以与^一起使用运算符。