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