如何对具有十六进制值的字符串执行按字节 XOR,以 C++ 为单位
How to perform a byte-wise XOR of a string with a hex value in C++?
假设我有字符串 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
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 我的神经网络不起作用 [XOR 问题]
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 在UNIX系统中使用DIR查找文件的字节大小
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- std::当在256字节边界上写入整数时,流的奇怪行为
- 当比特(而不是字节)的顺序至关重要时的持久性
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 如何在文件中查找字节序列
- luaL_dofile在已知良好的字节码上失败,可以使用未编译的版本
- 字节到位运算符重载C++
- 在java中读取c++字节的位字段
- 使用 std::vector::reverse_iterator 将 int 序列化为字节向量?
- 字节真的是最小可寻址单元吗
- struct.error:解压缩 C++ 结构时,解包需要 288 字节的缓冲区
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- 如何使用 OpenCV 解码在两个 UWP 应用之间发送的图像字节?
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 如何对具有十六进制值的字符串执行按字节 XOR,以 C++ 为单位
- 当到达空字节时,C++XOR失败