字符串编码转换

最近弄碰到字符串编码转换的问题,简单记录下

utf8 转 unicode

std::wstring UTF8ToWide(const std::string& source)
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
    return conv.from_bytes(source);
}

unicode 转 utf8

std::string WideToUTF8(const std::wstring& source)
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
    return conv.to_bytes(source);
}

utf8 转 utf16

std::u16string UTF8ToUTF16(const std::string& source)
{
    #if defined(OS_WIN)
    #if _MSC_VER >= 1900
    std::wstring_convert<std::codecvt_utf8_utf16<int16_t>, int16_t> conv;
    auto begin_pos = reinterpret_cast<const int8_t*>(source.data());
    return (char16_t*)conv.from_bytes((char*)begin_pos, (char*)(begin_pos + source.size())).c_str();
    #else
    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> conv;
    return conv.from_bytes(source);
    #endif
    #else
    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> conv;
    return conv.from_bytes(source);
    #endif
}

utf16 转 utf8

std::string UTF16ToUTF8(const std::u16string& source)
{
    #if defined(OS_WIN)
    #if _MSC_VER >= 1900
    std::wstring_convert<std::codecvt_utf8_utf16<int16_t>, int16_t> conv;
    auto begin_pos = reinterpret_cast<const int16_t*>(source.data());
    return conv.to_bytes(begin_pos, begin_pos + source.size());
    #else
    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> conv;
    return conv.to_bytes(source);
    #endif
    #else
    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> conv;
    return conv.to_bytes(source);
    #endif
}

Ascii 转unicode

std::wstring AsciiToWide(std::string _strSrc)
{
    int unicodeLen = MultiByteToWideChar(CP_ACP, 0, _strSrc.c_str(), -1, nullptr, 0);
    wchar_t *pUnicode = (wchar_t*)malloc(sizeof(wchar_t)*unicodeLen);
    MultiByteToWideChar(CP_ACP, 0, _strSrc.c_str(), -1, pUnicode, unicodeLen);
    std::wstring ret_str = pUnicode;
    free(pUnicode);
    return ret_str;
}

unicode 转 Ascii

std::string WideToAscii(std::wstring _strSrc)
{
    int ansiiLen = WideCharToMultiByte(CP_ACP, 0, _strSrc.c_str(), -1, nullptr, 0, nullptr, nullptr);
    char *pAssii = (char*)malloc(sizeof(char)*ansiiLen);
    WideCharToMultiByte(CP_ACP, 0, _strSrc.c_str(), -1, pAssii, ansiiLen, nullptr, nullptr);
    std::string ret_str = pAssii;
    free(pAssii);
    return ret_str;
}

utf8 转 Ascii

std::string UTF8ToAscii(std::string _strSrc)
{
    return WideToAscii(UTF8ToWide(_strSrc));
}

Ascii 转 utf8

std::string AsciiToUTF8(std::string _strSrc)
{
    return WideToUTF8(AsciiToWide(_strSrc));
}

深圳利程电子有限公司


所有图片均来自网络


   转载规则


《字符串编码转换》 smoking 采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
  目录