C++ 如何在C+中对具有十六进制值的字符串执行字节异或+;?

C++ 如何在C+中对具有十六进制值的字符串执行字节异或+;?,c++,hex,xor,C++,Hex,Xor,假设我有绳子 string str=“这是一个字符串” 和十六进制值 int值=0xbb 在C++中,如何使用十六进制值对字符串执行字节异或?只需迭代字符串并对每个字符进行异或: for (size_t i = 0; i < str.size(); ++i) str[i] ^= 0xbb; 另请参见。只需遍历字符串并对每个字符进行异或: for (size_t i = 0; i < str.size(); ++i) str[i] ^= 0xbb; 另请参见。您

假设我有绳子
string str=“这是一个字符串”

和十六进制值
int值=0xbb


在C++中,如何使用十六进制值对字符串执行字节异或?

只需迭代字符串并对每个字符进行异或:

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


另请参见。

只需遍历字符串并对每个字符进行异或:

for (size_t i = 0; i < str.size(); ++i)
    str[i] ^= 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);

您可以使用
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 ( char &c : str ) c ^= 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