求C++的16进制转UTF8的方法示例

例如string字符串“e4b88ae6b5b7”对应的是utf8下中文字符“上海”。求转换示例,需要跨平台。

https://blog.csdn.net/ndsman2007/article/details/106022352

#include <iostream>
#include <string>
#include <stdexcept>

using namespace std;

int to_int(char c)
{
    if (c >= '0' && c <= '9')
        return c - '0';
    if (c >= 'A' && c <= 'F')
        return c - 'A' + 10;
    if (c >= 'a' && c <= 'f')
        return c - 'a' + 10;
    throw std::invalid_argument("invalid input string");
}

string to_utf8(const std::string &str)
{
    if (str.length() % 2 != 0)
        throw std::invalid_argument("invalid input string");
    string r;
    char c;
    const char *p = str.c_str();
    while (*p)
    {
        c = to_int(*p++) * 16;
        c += to_int(*p++);
        r.push_back(c);
    }
    return r;
}

int main()
{
    string s = "e4b88ae6b5b7";
    cout << to_utf8(s) << endl;
    return 0;
}
$ g++ -Wall main.cpp
$ ./a.out
上海