gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:26:52 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com