[英]C++: Serialize byte array to hex string
我(C++ 新手)目前正在嘗試實現以下功能:
std::string bytes_to_hex(const std::string &bytes);
該函數應該基本上返回給定字節數組的 base16 編碼:
std::string input{0xde, 0xad, 0xbe, 0xef} => "deadbeef"
我的第一個版本並不像我想象的那樣工作:
std::string bytes_to_hex(const std::string &bytes) {
std::ostringstream ss;
ss << std::hex;
for (auto &c : bytes) {
ss << std::setfill('0') << std::setw(2) << +c;
}
return ss.str();
}
使用此函數,輸出為:
ffffffdeffffffadffffffbeffffffef
經過一些實驗,我發現這個版本看起來更好:
std::string bytes_to_hex(const std::string &bytes) {
std::ostringstream ss;
ss << std::hex;
for (const char &c : bytes) {
ss << std::setfill('0') << std::setw(2) << +(static_cast<uint8_t>(c));
}
return ss.str();
}
輸出如預期:
deadbeef
我的問題是:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.