我(C++新手)我目前正在努力實現以下功能: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();
}
使用此功能,outpu t是:
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
我的問題是:
- 爲什麼第二個版本和冷杉st不?這裏的主要區別是什麼?
- 第二個版本是否正確執行我的初衷還是會出現其他問題嗎?
'+'什麼都不做,但是做了你想要的東西,也就是確保字節被解釋爲正數 –
請記住'char'類型可以是'signed' *或*'unsigned',它是up編輯器。在你的情況下,它們似乎是'signed',這意味着當字符[升級爲'int'](http://en.cppreference.com/w/c/language/conversion#Integer_promotions)時,它們也是*符號擴展*。 –
@PasserBy角色的一元'+'力[*整數升級*](http://en.cppreference.com/w/c/language/conversion#Integer_promotions)。 –