stack_
stack_

Reputation: 35

Xor on two c++ string

I have two different length c++ strings.

string str1 = "01001110 01100001 01101101 01100101"

string str2 = "00000000 00000000 00000011"

I need to xor str1 and str2 and store the result in a new string

string xor_string =  str1 ^ str2

So, is it possible to xor two different length strings, and to store it into another string ?

I have searched for it but I didn't get it.

Can anyone tell me, how to do it?

Upvotes: 0

Views: 11005

Answers (2)

Thomas Matthews
Thomas Matthews

Reputation: 57718

You could always walk through or iterate through the string, and place the result into a new string.

std::string str1 = "01001110 01100001 01101101 01100101";
std::string str2 = "00000000 00000000 00000011";
//...  
std::string result;
const char c = ((str1[i] - '0') ^ (str2[i] - '0')) + '0';
result += c;

The fundamental issue is that you need to make the strings of equal length or change your algorithm to handle strings of different length.

For example, do you repeat str2 when str1 is longer or do you prefix str2 with '0'? This you will need to answer for yourself.

Upvotes: 1

Richard Hodges
Richard Hodges

Reputation: 69892

Something like this:

#include <string>
#include <iostream>
#include <bitset>
#include <algorithm>

std::bitset<32> to_bitset(std::string s)
{
    auto binary = [](char c) { return c == '0' || c == '1'; };
    auto not_binary = [binary](char c) { return !binary(c); };

    s.erase(std::remove_if(begin(s), end(s), not_binary), end(s));

    return std::bitset<32>(s);
}

std::string to_string(std::bitset<32> bs)
{
    return bs.to_string();
}

int main()
{
    std::string str1 = "01001110 01100001 01101101 01100101";
    std::string str2 = "00000000 00000000 00000011";

    auto result = to_string(to_bitset(str1) ^ to_bitset(str2));

    std::cout << result << std::endl;
}

expected output:

01001110011000010110110101100110

Upvotes: 5

Related Questions