将std::字节数组转换为十六进制std::字符串



我想要一种方法来获取任意大小的字节数组并返回十六进制字符串。专门用于记录通过网络发送的数据包,但我经常使用使用std::向量的等效函数。像这样的东西,可能是模板?

std::string hex_str(const std::array<uint8_t,??> array);

我已经搜索过了,但解决方案都说"将其视为c风格的数组"我特别想问的是,有没有办法不这样做。我想这没有出现在每个c++常见问题解答中是因为这是不可能的,如果是的话,有人能概括一下为什么吗?

我已经有了这些重载,第二个重载可以通过衰变成c风格的数组来用于std::数组,所以请不要告诉我怎么做。

std::string hex_str(const std::vector<uint8_t> &data);
std::string hex_str(const uint8_t *data, const size_t size);

(编辑:向量是我的代码中的引用)

您应该考虑像标准算法那样编写与迭代器一起工作的函数。然后,您可以将其用于std::vectorstd::array输入,例如:

template<typename Iter>
std::string hex_str(Iter begin, Iter end)
{
std::ostringstream output;
output << std::hex << std::setw(2) << std::setfill('0');
while(begin != end)
output << static_cast<unsigned>(*begin++);
return output.str();
}

在线演示如果你真的想避免在你传入的容器上调用begin()/end(),你可以定义一个帮助器来处理,例如:

template<typename C>
std::string hex_str(const C &data) {
return hex_str(data.begin(), data.end());
}

在线演示或者,如果你真的想的话,你可以把这些都压缩成一个函数,例如:

template <typename C>
std::string hex_str(const C& data)
{
std::ostringstream output;
output << std::hex << std::setw(2) << std::setfill('0');
for(const auto &elem : data)
output << static_cast<unsigned>(elem);
return output.str();
}

在线演示

如果您在编译时知道std::array的大小,则可以使用非类型模板参数。

template<std::size_t N>
std::string hex_str( const std::array<std::uint8_t, N>& buffer )
{ /* Implementation */ }
int main( )
{   
// Usage.
std::array<std::uint8_t, 5> bytes = { 1, 2, 3, 4, 5 };
const auto value{ hex_str( bytes ) };
}

或者你可以只模板整个容器(减少你的重载)。

template<typename Container>
std::string hex_str( const Container& buffer ) 
{ /* Implementaion */ }
int main( )
{   
// Usage.
std::array<std::uint8_t, 5> bytes = { 1, 2, 3, 4, 5 };
const auto value{ hex_str( bytes ) };
}

最新更新