Siddharth Sharma
Siddharth Sharma

Reputation: 182

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.

Upvotes: 2

Views: 17900

Answers (6)

Abhishek Gupta
Abhishek Gupta

Reputation: 1

It would be better for different sizes of strings. :)

string XOR(string a, string b){

    ll la = a.length();
    ll lb = b.length();
    string X;
    X = (la > lb ) ? a : b;

    ll i=(la>lb)?la-1:lb-1, j = (la<lb)?la-1:lb-1,x=(la>lb? la-1:lb-1) ;
    for(;i>=0,j>=0;i--,j--,x--){

        X[x] =  (la>lb)? ( a[i] ^ b[j] )+'0' : ( b[i] ^ a[j] )+'0'; 
    }


    return X;
} 

Upvotes: 0

dhruv sharma
dhruv sharma

Reputation: 61

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.

Upvotes: 0

Gaurav Sehgal
Gaurav Sehgal

Reputation: 7542

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

Upvotes: 0

Richard Hodges
Richard Hodges

Reputation: 69892

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

Upvotes: 4

Benson Lin
Benson Lin

Reputation: 1404

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

Upvotes: 9

user2249683
user2249683

Reputation:

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

Upvotes: 3

Related Questions