2015-12-22 85 views
0

我有一個包含十六進制值的字節數組。要存儲它,我將它編碼爲字符串,並首先檢索它,然後將其解碼爲字符串,那麼如何將它轉換爲字節數組呢?如何將字符串轉換爲字節數組

下面是代碼:

我創建的字節數組的位置:

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 

我們得到主要的字節數組,第一我解碼它:

​​

但我不知道如何達到字節數組。

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

回答

0

我認爲這對您的編碼效果會更好。假設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; 
} 
0
key = (byte *)decodedkey.data(); 
相關問題