Siddharth Sharma Siddharth Sharma - 2 months ago 12
C++ Question

XOR two Binary Strings c++

I have two strings as follows :

STRING1 : 011011110011000

STRING2 : 011001000001000

EXPECTED OUTPUT : 000010110010000


However, when i try to XOR them(bit-wise) using the following code, the output is blank.
Code:

for(int i = 0; i<15; i++)
{
final_key[i] = STRING1[i] ^ STRING2[i];
cout<<" XOR = "<<final_key[i];
}


Any help would be appreciated.

Answer

You are trying to XOR 2 char at a time. Try instead:

final_key[i] = ((STRING1[i]-'0') ^ (STRING2[i]-'0')) + '0'; 

Explanation

Refer to here for ASCII values.

The ASCII value for '0' is 48 and the ASCII value of '1' is 49. 48 ^ 49 is 1, 48 ^ 48 and 49 ^ 49 is 0. These would return a value of 0 or 1 to a char, which would stand for either a EOF char (if it is 0) or a SOH char (if it is one), neither of which are output correctly.

Thus you would want to convert each char into a bit (0 or 1) before conducting the XOR operation. Thus you can subtract '0' from each char to get the numrical value of the digit, conduct the XOR operation, then add back '0' to get a proper output

Comments