1. 程式人生 > >C++ UTF8 互轉 Unicode

C++ UTF8 互轉 Unicode

C++/MFC   UTF8 轉 Unicode

char* U8ToUnicode(char* szU8)
{
    //UTF8 to Unicode
    //預轉換,得到所需空間的大小
    int wcsLen = ::MultiByteToWideChar(CP_UTF8, NULL, szU8, strlen(szU8), NULL, 0);
    //分配空間要給'\0'留個空間,MultiByteToWideChar不會給'\0'空間
    wchar_t* wszString = new wchar_t[wcsLen + 1];
    //轉換
    ::MultiByteToWideChar(CP_UTF8, NULL, szU8, strlen(szU8), wszString, wcsLen);
    //最後加上'\0'
    wszString[wcsLen] = '\0';

    char *m_char;
    int len = WideCharToMultiByte(CP_ACP, 0, wszString, wcslen(wszString), NULL, 0, NULL, NULL);
    m_char = new char[len + 1];
    WideCharToMultiByte(CP_ACP, 0, wszString, wcslen(wszString), m_char, len, NULL, NULL);
    m_char[len] = '\0';
    return m_char;
}

Unicode 轉  UTF8

char* UnicodeToU8(wchar_t* wszString)
{
    // unicode to UTF8
    //預轉換,得到所需空間的大小,這次用的函式和上面名字相反
    int u8Len = ::WideCharToMultiByte(CP_UTF8, NULL, wszString, wcslen(wszString), NULL, 0, NULL, NULL);
    //同上,分配空間要給'\0'留個空間
    //UTF8雖然是Unicode的壓縮形式,但也是多位元組字串,所以可以以char的形式儲存
    char* szU8 = new char[u8Len + 1];
    //轉換
    //unicode版對應的strlen是wcslen
    ::WideCharToMultiByte(CP_UTF8, NULL, wszString, wcslen(wszString), szU8, u8Len, NULL, NULL);
    //最後加上'\0'
    szU8[u8Len] = '\0';
    return szU8;
}