UTF8與GBK字符編碼轉換

utf8與gbk字符之間的轉換主要用到兩個方法

WideCharToMultiByte:http://baike.baidu.com/view/2083430.htm?fr=aladdin

MultiByteToWideChar:http://baike.baidu.com/view/1907282.htm?fr=aladdin

使用這兩個方法就可以成功轉換。

將GBK轉換成UTF8

std::string GBKtoUTF8(const std::string& str)
{
    std::string strout = "";
    WCHAR * strGBK;
    int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
    strGBK = new WCHAR[len];
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, strGBK, len);

    len = WideCharToMultiByte(CP_UTF8, 0, strGBK, -1, NULL, 0, NULL, NULL);
    char * strUTF8 = new char[len];
    WideCharToMultiByte(CP_UTF8, 0, strGBK, -1, strUTF8, len, NULL, NULL);

    //memcpy(str, strUTF8, strlen(strUTF8));

    strout = strUTF8;

    delete[] strGBK;
    strGBK = NULL;
    delete[] strUTF8;
    strUTF8 = NULL;

    return strout;
}
將UTF8轉換成GBK

std::string UTF8toGBK(const std::string& strint)
{
    std::string strout = "";
    int len = MultiByteToWideChar(CP_UTF8, 0, strint.c_str(), -1, NULL, 0);
    unsigned short * wszGBK = new unsigned short[len + 1];
    memset(wszGBK, 0, len * 2 + 2);
    MultiByteToWideChar(CP_UTF8, 0, strint.c_str(), -1, (LPWSTR)wszGBK, len);

    len = WideCharToMultiByte(CP_ACP, 0, (LPWSTR)wszGBK, -1, NULL, 0, NULL, NULL);
    char *szGBK = new char[len + 1];
    memset(szGBK, 0, len + 1);
    WideCharToMultiByte(CP_ACP,0, (LPWSTR)wszGBK, -1, szGBK, len, NULL, NULL);
    //strUTF8 = szGBK;
    //memcpy(strout, szGBK, strlen(szGBK));

    strout = szGBK;

    delete[]szGBK;
    delete[]wszGBK;

    return strout;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章