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++?
Just iterate through the string and XOR each character:
for (size_t i = 0; i < str.size(); ++i)
str[i] ^= 0xbb;
or perhaps more idiomatically in C++11 and later:
for (char &c : str)
c ^= 0xbb;
See also this question.
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);
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