C++ 字符串編碼轉(zhuǎn)換

? 最近碰到字符串編碼轉(zhuǎn)換的問題,簡單記錄下

utf8 轉(zhuǎn) unicode

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

unicode 轉(zhuǎn) utf8

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

utf8 轉(zhuǎn) 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 轉(zhuǎn) 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 轉(zhuǎn)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 轉(zhuǎn) 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 轉(zhuǎn) Ascii

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

Ascii 轉(zhuǎn) utf8

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

深圳利程電子有限公司

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容