c++ - 将 ASCII std::string 转换为十六进制

标签 c++ ascii

有没有一种简单的方法可以将 ASCII std::string 转换为 HEX?我不想将它转换为数字,我只想将每个 ASCII 字符转换为它的 HEX 值。输出格式也应该是 std::string。 即:“TEST”将是“0x54 0x45 0x53 0x54”或一些类似的格式。

我找到了这个解决方案,但也许有更好的解决方案(没有字符串到 int 到字符串的转换):

std::string teststring = "TEST";
std::stringstream hValStr;
for (std::size_t i=0; i < teststring.length(); i++)
{
    int hValInt = (char)teststring[i];
    hValStr << "0x" << std::hex << hValInt << " ";
}

谢谢,
/mspoerr

最佳答案

如果您不关心 0x,使用 std::copy 很容易做到:

#include <algorithm>
#include <sstream>
#include <iostream>
#include <iterator>
#include <iomanip>

namespace {
   const std::string test="hello world";
}

int main() {
   std::ostringstream result;
   result << std::setw(2) << std::setfill('0') << std::hex << std::uppercase;
   std::copy(test.begin(), test.end(), std::ostream_iterator<unsigned int>(result, " "));
   std::cout << test << ":" << result.str() << std::endl;
}

关于c++ - 将 ASCII std::string 转换为十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5990825/

相关文章:

sql - varchar()中的十六进制字符实际上是ascii。需要解码

c++ - 二元运算符 + , = 用 const 重载

c++ - 如何根据表达式在 Boost.Hana 中是否有效来过滤类型元组?

c++ - boost::lexical_cast<signed char> 无法处理负数?

ruby - 如何在 Ruby 中打印转义字符?

Python 字符串打印为 [u'String']

c++ - lcov 将带有函数声明的行标记为可达但未被覆盖

c++ - 添加水平滚动条到控制台

c - 如何在 Ascii 中进行数学运算?

C: 转换特殊 ASCII 字符 ÁÖÜ