将 uint8 向量转换为 ascii 十六进制字符串的更好方法 [英] Better way to convert a vector of uint8 to an ascii hexadecimal string
本文介绍了将 uint8 向量转换为 ascii 十六进制字符串的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了以下函数来将 uint8_t
的 std::vector
转换为 ascii 十六进制 string
(gnu++98 标准).
I coded the following function to convert a std::vector
of uint8_t
to an ascii hexadecimal string
(gnu++98 standard).
...
string uint8_vector_to_hex_string(const vector<uint8_t>& v) {
stringstream ss;
vector<uint8_t>::const_iterator it;
for (it = v.begin(); it != v.end(); it++) {
char hex_char[2];
sprintf(hex_char, "%x", *it);
ss << "\\x" << hex_char;
}
return ss.str();
}
...
它工作正常.我想知道是否有更好的方法来进行这种转换,也许不是同时使用 stringstream
对象和 sprintf
函数.有什么建议吗?
It works fine. I was wondering if there is a better way to do this transformation, maybe using not both the stringstream
object and the sprintf
function. Any suggestion?
推荐答案
您可以直接使用 stringstream 进行十六进制格式化:
You could use the stringstream directly to do hex formatting:
#include <string>
#include <sstream>
#include <iostream>
...
string uint8_vector_to_hex_string(const vector<uint8_t>& v) {
stringstream ss;
ss << std::hex << std::setfill('0');
vector<uint8_t>::const_iterator it;
for (it = v.begin(); it != v.end(); it++) {
ss << "\\x" << std::setw(2) << static_cast<unsigned>(*it);
}
return ss.str();
}
...
这篇关于将 uint8 向量转换为 ascii 十六进制字符串的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文