Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xor on two hexadeicmal values stored as string in c++

Tags:

c++

xor

I have two hexadecimal values which is stored as string:

string md5OfPath("a77e0a3e517e0a9d44c3a823d96ca83c");
string guidValue("c3b491e559ac4f6a81e527e971b903ed");

I want to perform XOR operation on both the values in C++. Can you please suggest me on how I can perform the xor operation.

like image 491
sanam_bl Avatar asked Oct 01 '12 10:10

sanam_bl


People also ask

How do you find the XOR of two hexadecimal numbers?

The XOR is commutative so it starts with the first two hexadecimal numbers, XORs them together, and gets the result. Then it XORs the result with the third hexadecimal and gets the next result.

Can you XOR strings C++?

The answer is yes. You will need to either truncate one string, or extend the other string. Note that the xor operation is not defined on strings (because they usually contain other characters than just zeros and ones), you will have to define it yourself.


1 Answers

I think the straight-forward loop should do the trick:

static inline unsigned int value(char c)
{
    if (c >= '0' && c <= '9') { return c - '0';      }
    if (c >= 'a' && c <= 'f') { return c - 'a' + 10; }
    if (c >= 'A' && c <= 'F') { return c - 'A' + 10; }
    return -1;
}

std::string str_xor(std::string const & s1, std::string const & s2)
{
    assert(s1.length() == s2.length());

    static char const alphabet[] = "0123456789abcdef";

    std::string result;
    result.reserve(s1.length());

    for (std::size_t i = 0; i != s1.length(); ++i)
    { 
        unsigned int v = value(s1[i]) ^ value(s2[i]);

        assert(v < sizeof alphabet);

        result.push_back(alphabet[v]);
    }

    return result;
}
like image 163
Kerrek SB Avatar answered Oct 12 '22 23:10

Kerrek SB