假设我有字符串 string str = "this is a string";
和十六进制值 int value = 0xbb;
我将如何对字符串执行 XOR 的十六进制值C++?
只需遍历字符串并 XOR 每个字符:
for (size_t i = 0; i < str.size(); ++i)
str[i] ^= 0xbb;
现场演示
或者也许在 C++11 及更高版本中更习惯:
for (char &c : str)
c ^= 0xbb;
现场演示
另请参阅此问题。
您可以使用 std::for_each
进行迭代,并应用 lambda 来执行该操作。
std::for_each(str.begin(), str.end(), [](char &x){ x ^= 0xbb; });
或函子:
struct { void operator()(char &x) { x ^= 0xbb; } } op;
std::for_each(str.begin(), str.end(), op);
有几种方法可以完成这项任务。例如
for ( char &c : str ) c ^= value;
或
for ( std::string::size_type i = 0; i < str.size(); i++ )
{
str[i] ^= value;
}
或
#include <algorithm>
//...
std::for_each( str.begin(), std::end(), [&]( char &c ) { c ^= value; } );
或
#include <algorithm>
#include <functional>
//...
std::transform( str.begin(), std.end(),
str.begin(),
std::bind2nd( std::bit_xor<char>(), value ) );
这是一个演示程序
#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;
}
它的输出是
this is a string
this is a string
this is a string