如何对具有十六进制值的字符串执行按字节 XOR,以 C++ 为单位

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

本文关键字:XOR 字节 为单位 C++ 执行 字符串 十六进制      更新时间:2023-10-16

假设我有字符串 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