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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With