如何将一串十六进制值转换为一个字符串?

2022-01-07 00:00:00 string ascii c++ stl

假设我有一个字符串:

string hex = "48656c6c6f";

其中每两个字符对应于其 ASCII 值的十六进制表示,例如:

Where every two characters correspond to the hex representation of their ASCII, value, eg:

0x48 0x65 0x6c 0x6c 0x6f = "Hello"

那么如何从 "48656c6c6f" 获取 "hello" 而不必创建查找 ASCII 表?atoi() 显然在这里不起作用.

So how can I get "hello" from "48656c6c6f" without having to create a lookup ASCII table? atoi() obviously won't work here.

推荐答案

int len = hex.length();
std::string newString;
for(int i=0; i< len; i+=2)
{
    std::string byte = hex.substr(i,2);
    char chr = (char) (int)strtol(byte.c_str(), null, 16);
    newString.push_back(chr);
}

相关文章