簡體   English   中英

如何將字符串轉換為字節數組

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

我認為這將對您更好地進行編碼。 假設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] = '\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