【问题标题】:Convert bytes array to Hexadecimal String [duplicate]将字节数组转换为十六进制字符串[重复]
【发布时间】:2017-07-16 00:19:45
【问题描述】:

这是我为 Print a byte array to hex String 编写的,但现在我想将它们保存为 std::string 并稍后使用

这是我的代码

typedef std::vector<unsigned char> bytes;
void printBytes(const bytes &in)
{
    std::vector<unsigned char>::const_iterator from = in.begin();
    std::vector<unsigned char>::const_iterator to = in.end();
    for (; from != to; ++from) printf("%02X", *from);
}

我能做什么?,我想将它保存为字符串而不是在控制台窗口中打印(显示)? 任何想法!

【问题讨论】:

  • "在 C++ 中没有类似 StringBuilder 的函数" - 是的,有。它被称为std::ostringstream

标签: c++


【解决方案1】:

使用std::ostringstream:

typedef std::vector<unsigned char> bytes;
std::string BytesToStr(const bytes &in)
{
    bytes::const_iterator from = in.cbegin();
    bytes::const_iterator to = in.cend();
    std::ostringstream oss;
    for (; from != to; ++from)
       oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(*from);
    return oss.str();
}

【讨论】:

  • static_cast&lt;int&gt;() 在 C++ 中会比 C 风格的演员 (int) 更惯用。
  • 如果要将0x附加到前面,请使用std::showbase
  • @phoenix 你将如何将此字符串转换回来?
  • @anc:您可以将std::hexstd::setw()std::istringstreamoperator&gt;&gt; 一起使用
猜你喜欢
  • 2021-04-13
  • 2018-03-24
  • 2018-05-09
  • 1970-01-01
  • 2021-10-31
  • 2019-02-12
相关资源
最近更新 更多