Xor binary strings in java

I am using the following code for 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 the correct output:

 0000000000001111001100110000011110110000000011000111001011011000 

I need XOR another line

 String hseq = "0011111111110010010111110100010111100000101101001110000100011110"; 

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

I get the result:

 48484848484848484848484948484948494848494848494949484848494848494848494849494848484949494948484848484948494948494949484948484948 

which is wrong. I need help executing xor three binary strings

+7
source share
3 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); } 

What are the exits

 0011111111111101011011000100001001010000101110001001001111000110 
+8
source

You can use BigInteger , this will simplify your code. It has a constructor in which you can pass the string and the base you want to use (2 in your case).

Then you can make an XOR call to public BigInteger xor(BigInteger val) (see docs or take a look at openjdk BigInteger Code )

0
source

You may 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, char treated as an int in the sense that a numeric value represents a predefined character. We can subtract the value of the character '0' from our character (knowing that the value of '1' is only 1 greater than '0') and get either 0 or 1, which can be used with the ^ operator.

0
source

All Articles