[英]Store multiple hex values in a string c++
我想將整數數組轉換為十六進制形式,然后將所有十六進制值連接成一個C ++字符串。 整數最初是uint8_t
,但我讀到了如何將它們毫無問題地轉換為int
。 到目前為止,我有這個。
for (int i = 0; i < HASHLEN; ++i) {
int a = static_cast< int >(hash2[i]); // convert the uint8_t to a int
cout << setfill('0') << setw(2) << hex << a; // print the hex value with the leading zero (important)
}
這段代碼在一行上打印數組中每個int的十六進制值,如下所示:
41a9ffb9588717989367b3ec942233d5d9a982f8658c1073a87262da43fd42c9
如何將該值存儲為字符串? 我嘗試創建一個string hash = "";
在循環之前使用此行:
hash = hash + to_string(setfill('0') + setw(2) + hex + a);
而不是cout
,但這是行不通的。 如果您想知道,錯誤是
error: invalid operands to binary expression ('__iom_t4<char>' and 'std::__1::__iom_t6')
用std::stringstream
替換cout
將完成以下工作:
std::stringstream hexstr;
for (int i = 0; i < HASHLEN; ++i) {
int a = static_cast< int >(hash2[i]);
hexstr << setfill('0') << setw(2) << hex << a;
}
std::string res = hexstr.str();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.