Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xor of binary strings in java

Tags:

java

i am using the following code to XOR 2 strings

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);

The above code gives me correct output :

0000000000001111001100110000011110110000000011000111001011011000

I need to XOR one more string

String hseq = "0011111111110010010111110100010111100000101101001110000100011110";

if i try sb.append((lseq.charAt(i) ^ tseq.charAt(i) ^ hseq.charAt(i));

I am getting result :

48484848484848484848484948484948494848494848494949484848494848494848494849494848484949494948484848484948494948494949484948484948

which is wrong. I need help in doing xor of 3 binary strings

like image 440
Kailash Avatar asked Dec 23 '13 14:12

Kailash


2 Answers

I would do it like this

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);
}

Which outputs

0011111111111101011011000100001001010000101110001001001111000110
like image 191
Elliott Frisch Avatar answered Sep 27 '22 19:09

Elliott Frisch


You could also consider something like this:

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);

Under the hood, a char is treated like an int in that the numeric value represents a pre-defined character. We can subtract the value of the character '0' from our character (knowing that the value of '1' is only 1 more than '0') and get either 0 or 1, which can be used with the ^ operator.

like image 31
ian Avatar answered Sep 27 '22 21:09

ian