XOR two Binary Strings c++

房东的猫 提交于 2019-12-06 12:45:06

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

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

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';
dhruv sharma
string strings_xor(string s, string t) {

string res = "";
for(int i = 0; i < s.size(); i++) {
    if(s[i] == t[i])
        res += '0';
    else
        res += '1';
}

return res;
}

hope this helps.

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');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!