如何将字符串转换为字节数组
How to convert string to byte array
我有一个包含十六进制值的字节数组。为了存储它,我将其编码为字符串,并首先将其检索,我将它解码为字符串,然后如何将其转换为字节数组?
这是代码:
我在这里创建字节数组:
AutoSeededRandomPool prng;
byte key[CryptoPP::AES::MAX_KEYLENGTH];
prng.GenerateBlock(key, sizeof(key));
然后用以下代码将其编码为字符串:
string encoded;
encoded.clear();
StringSource(key, sizeof(key), true,
new HexEncoder(
new StringSink(encoded)
) // HexEncoder
); // StringSource
现在要获得主字节数组,首先我对其进行解码:
string decodedkey;
StringSource ssk(encoded, true /*pumpAll*/,
new HexDecoder(
new StringSink(decodedkey)
) // HexDecoder
); // StringSource
但我不知道如何到达字节数组。
byte key[CryptoPP::AES::MAX_KEYLENGTH];
我认为这将更好地用于编码。假定byte
是unsigned char
的typedef。
std::stringstream ss;
ss.fill('0');
ss.width(2);
for (int x = 0; x < CryptoPP::AES::MAX_KEYLENGTH; x++)
{
unsigned int val = (unsigned int)bytes[x];
ss << std::hex << val; // writes val out as a 2-digit hex char
}
std::string result = ss.str(); // result is a hex string of your byte array
以上将把字节数组(如{1,99,200}
)转换为"0163C8"
然后将字符串解码回字节数组:
byte key[MAX_KEYLENGTH] = {};
for (int x = 0; x < MAX_KEYLENGTH; x++)
{
char sz[3];
sz[0] = result[x*2];
sz[1] = result[x*2+1];
sz[2] = ' ';
unsigned char val = (unsigned char)strtoul(sz, NULL, 10);
bytes[x] = val;
}
key = (byte *)decodedkey.data();
相关文章:
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 基于字节数组生成静态范围整数值
- 将字节数组转换为带有字节序问题的指针
- 找到一种有效的方法,在 2 个巨大的缓冲区上执行 MAX,每字节字节
- 使用 stbi_write_png,如何将 0 和 1 的矩形字节数组转换为单色 png 文件?
- 字节数组初始化会导致 DirectX 崩溃
- 使用 swig 追加到字节数组
- C++ 替换字节数组中项的顺序
- QDataStream 读取和写入的字节数比 QFile::length() 报告要多
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 如何通过libpq c api插入字节的数组
- i2c中的字节指针数组
- 以 C++ 为单位递增 16 字节字符数组
- new[] 一个包含构造函数的字节对象数组没有错,对吧?
- 创建未知长度的字节/字符数组
- 我如何将bitset转换为字节/uint8数组
- C++ <--> C# 修改字节编组数组
- 将m个字节的数组拆分为n个字节的块
- c++到c#:有3个元素的字节指针数组等于什么?