如何将字符串转换为字节数组

How to convert string to byte array

本文关键字:字节 字节数 数组 转换 字符串      更新时间:2023-10-16

我有一个包含十六进制值的字节数组。为了存储它,我将其编码为字符串,并首先将其检索,我将它解码为字符串,然后如何将其转换为字节数组?

这是代码:

我在这里创建字节数组:

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]; 

我认为这将更好地用于编码。假定byteunsigned 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();