2

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++?

Tim Wong
  • 67
  • 1
  • 6

3 Answers3

5

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.

Community
  • 1
  • 1
Paul R
  • 208,748
  • 37
  • 389
  • 560
2

You can iterate using std::for_each, and apply a lambda to do the operation.

std::for_each(str.begin(), str.end(), [](char &x){ x ^= 0xbb; });

Or a functor:

struct { void operator()(char &x) { x ^= 0xbb; } } op;
std::for_each(str.begin(), str.end(), op);
jxh
  • 69,070
  • 8
  • 110
  • 193
2

There are several ways to do the task. For example

for ( char &c : str ) c ^= value;

or

for ( std::string::size_type i = 0; i < str.size(); i++ )
{
    str[i] ^= value;
}   

or

#include <algorithm>

//...

std::for_each( str.begin(), std::end(), [&]( char &c ) { c ^= value; } );

or

#include <algorithm>
#include <functional>


//...

std::transform( str.begin(), std.end(), 
                str.begin(),
                std::bind2nd( std::bit_xor<char>(), value ) );

Here is a demonstrative program

#include <iostream>
#include <string>
#include <algorithm>
#include <functional> 

int main()
{
    std::string s( "this is a string" );
    int value = 0xBB;

    std::cout << s << std::endl;

    for ( char &c : s ) c ^= value;

    for ( std::string::size_type i = 0; i < s.size(); i++ )
    {
        s[i] ^= value;
    }

    std::cout << s << std::endl;

    std::for_each( s.begin(), s.end(), [&]( char &c ) { c ^= value; } );

    std::transform( s.begin(), s.end(),
                    s.begin(),
                    std::bind2nd( std::bit_xor<char>(), value ) );

    std::cout << s << std::endl;
}

Its output is

this is a string
this is a string
this is a string
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335