将ASCII std :: string转换为十六进制 [英] Convert an ASCII std::string to hex

查看:1768
本文介绍了将ASCII std :: string转换为十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个简单的方法来将ASCII std :: string转换为HEX?我不想将其转换为一个数字,我只想将每个ASCII字符转换为它的十六进制值。输出格式也应该是std :: string。
ie:TEST将是0x54 0x45 0x53 0x54或一些类似的格式。

is there an easy way to convert an ASCII std::string to HEX? I don't want to convert it to a number, I only want to convert each ASCII character to it's HEX value. The output format should also be a std::string. i.e.: "TEST" would be "0x54 0x45 0x53 0x54" or some similar format.

我发现这个解决方案,但也许有一个更好的无字符串到字符串转换):

I found this solution, but maybe there is a better one (without string to int to string conversion):

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

Thanks,
/mspoerr

推荐答案

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

If you don't care about the 0x it's easy to do using 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;
}

这篇关于将ASCII std :: string转换为十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆