简体   繁体   English

将ASCII std :: string转换为hex

[英]Convert an ASCII std::string to hex

is there an easy way to convert an ASCII std::string to HEX? 有一种简单的方法将ASCII std :: string转换为HEX? I don't want to convert it to a number, I only want to convert each ASCII character to it's HEX value. 我不想将它转换为数字,我只想将每个ASCII字符转换为它的HEX值。 The output format should also be a std::string. 输出格式也应该是std :: string。 ie: "TEST" would be "0x54 0x45 0x53 0x54" or some similar format. 即:“TEST”将是“0x54 0x45 0x53 0x54”或类似的格式。

I found this solution, but maybe there is a better one (without string to int to string conversion): 我找到了这个解决方案,但也许有一个更好的解决方案(没有字符串到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 << " ";
}

Thanks, 谢谢,
/mspoerr / mspoerr

If you don't care about the 0x it's easy to do using std::copy : 如果你不关心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;
}

This answer to another question does what you want, I think. 我想,对另一个问题的答案可以满足您的需求。 You'd have to add a " " as separator argument for the ostream_iterator to get whitespaces between the characters. 您必须为ostream_iterator添加一个" "作为分隔符参数,以获取字符之间的空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM