-->

XOR two Binary Strings c++

2019-05-19 02:35发布

问题:

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.

回答1:

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



回答2:

c++ has std::bitset<>

#incude <string>
#incude <bitset>
#incude <iostream>

int main()
{
    std::string s1 = "010101010101010101";
    std::string s2 = "101010101000001111";

    auto result = std::bitset<32>(s1) ^ std::bitset<32>(s2);
    std::cout << result << std::endl;
}


回答3:

The ASCII values of the characters '0' and '1' are 48 and 49. To apply an XOR on two characters a,b ∈ { '0', '1' } you may use:

char result = std::abs(a - b) + '0';


回答4:

You are Xoring characters.That works but you are storing the result as it is without converting the result into character.

string s1="011011110011000";
string s2="011001000001000";
char final_key[15];
for(int i = 0; i<15; i++)
 {
final_key[i] = (s1[i] ^ s2[i])+'0'; //paranthesis is important
cout<<final_key[i];
}

You could also check whether s1[i] is not equal to s2[i], then result is 1

final_key[i]=(s1[i]!=s2[i]?'1':'0');