【问题标题】:Convert an ASCII std::string to hex将 ASCII std::string 转换为十六进制
【发布时间】:2011-08-24 20:26:55
【问题描述】:

有没有一种简单的方法可以将 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

【问题讨论】:

    标签: c++ ascii


    【解决方案1】:

    如果您不关心 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;
    }
    

    【讨论】:

    • 如果你愿意,我会发布一个更新版本,展示如何添加 0x?
    • 不幸的是,这不适用于 0xFF 等 ASCII 字符。我使用 string::read() 函数读取一个无符号字符数组,其 ASCII 值 > 0x7F。您的解决方案需要进行哪些更改才能使其在我的场景中运行?再次感谢...
    • @mspoerr:没有值为 0xFF 的 ASCII 字符。不可能,因为 ASCII 是 7 位字符集。这也是为什么char 可能会或可能不会被签名的原因; ASCII 真的没关系。 char(0x7F) 总是积极的。
    • 我的意思是8位版本,但是它被称为(扩展ASCII左右)。
    • 这不会使 setw(2) 和 setfill('0') 超出字符串的第一个元素。
    【解决方案2】:

    This answer 对另一个问题做你想要的,我想。您必须添加一个 " " 作为 ostream_iterator 的分隔符参数,以获取字符之间的空格。

    【讨论】:

    • +1 表示不重复内容!在我的快速搜索中没有发现。
    • @awoodland:我只记得以前几乎完全回答过这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 2012-11-09
    • 2017-10-13
    • 2016-09-27
    • 2011-11-21
    • 1970-01-01
    相关资源
    最近更新 更多