VC: MBCS字符集转换成UTF-8

来源:互联网 发布:中文安卓编程王者荣耀 编辑:程序博客网 时间:2024/05/17 01:27


// MBCS字符集转换成UTF-8,使用完了之后要释放返回的内存!
char* DataStore::MBCS2Utf8(char* szMBCS, ULONG* _out_length)
{
    if (szMBCS == NULL || _out_length == NULL)
        return NULL;
    // 方法:先转换成CP_ACP再转换成CP_UTF8
    int nLength = MultiByteToWideChar(CP_ACP, 0, szMBCS, -1, NULL, NULL);   // 获取缓冲区长度,再分配内存
    WCHAR *tch = new WCHAR[nLength];
     
    nLength = MultiByteToWideChar(CP_ACP, 0, szMBCS, -1, tch, nLength);     // 将MBCS转换成Unicode
 
    int nUTF8len = WideCharToMultiByte(CP_UTF8, 0, tch, nLength, 0, 0, 0, 0);   // 获取UTF-8编码长度
    char *utf8_string = new char[nUTF8len];
    WideCharToMultiByte(CP_UTF8, 0, tch, nLength, utf8_string, nUTF8len, 0, 0); //转换成UTF-8编码
    *_out_length = nUTF8len;
 
    delete tch;
    return utf8_string;
}
0 0
原创粉丝点击