简体   繁体   English

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

[英]How to convert string to byte array

I have a byte array which contain hex value. 我有一个包含十六进制值的字节数组。 To store it I encode it to string, and to retrieve it first I decode it to string, how can I convert it to byte array then? 要存储它,我将其编码为字符串,然后首先将其解码为字符串,然后如何将其转换为字节数组?

Here is the code : 这是代码:

I create byte array here: 我在这里创建字节数组:

AutoSeededRandomPool prng;
byte key[CryptoPP::AES::MAX_KEYLENGTH];

prng.GenerateBlock(key, sizeof(key));

and then encode it as string with following: 然后使用以下代码将其编码为字符串:

string encoded;
encoded.clear();
StringSource(key, sizeof(key), true,
    new HexEncoder(
        new StringSink(encoded)
    ) // HexEncoder
); // StringSource

Now to get main byte array, first I decode it: 现在获取主字节数组,首先我将其解码:

string decodedkey;
StringSource ssk(encoded, true /*pumpAll*/,
new HexDecoder(
    new StringSink(decodedkey)
    ) // HexDecoder
); // StringSource

but I don't know how to reach to byte array. 但是我不知道如何到达字节数组。

byte key[CryptoPP::AES::MAX_KEYLENGTH]; 

I think this will work better for you for encoding. 我认为这将对您更好地进行编码。 Assumes byte is a typedef for unsigned char . 假设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

The above will convert a byte array such as {1,99,200} into "0163C8" 上面的代码会将字节数组(例如{1,99,200}转换为"0163C8"

Then to decode the string back to the byte array: 然后将字符串解码回字节数组:

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] = '\0';
    unsigned char val = (unsigned char)strtoul(sz, NULL, 10);
    bytes[x] = val;
}
key = (byte *)decodedkey.data();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM