Search code examples
c++hexxor

How to perform a byte-wise XOR of a string with a hex value in C++?


Let's say I have the string string str = "this is a string";

and a hexadecimal value int value = 0xbb;

How would I go about performing a byte-wise XOR of the string with the hex value in C++?


Solution

  • Just iterate through the string and XOR each character:

    for (size_t i = 0; i < str.size(); ++i)
        str[i] ^= 0xbb;
    

    LIVE DEMO

    or perhaps more idiomatically in C++11 and later:

    for (char &c : str)
        c ^= 0xbb;
    

    LIVE DEMO

    See also this question.