C++ UTF8和GB2312相互转换

#include <Windows.h>
#include <string>
using std::string;

void UTF8_to_GB2312(const char* utf8, string& gb2312_str)
{
    int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
    wchar_t* wstr = new wchar_t[len+1];
    memset(wstr, 0, len+1);
    MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
    len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
    char* str = new char[len+1];
    memset(str, 0, len+1);
    WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
    delete[] wstr;
    gb2312_str = str;
    delete[] str;
    return;
}

void GB2312_to_UTF8(const char* gb2312, string& utf8_str)
{
    int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0);
    wchar_t* wstr = new wchar_t[len+1];
    memset(wstr, 0, len+1);
    MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len);
    len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
    char* str = new char[len+1];
    memset(str, 0, len+1);
    WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
    delete[] wstr;
    utf8_str = str;
    delete[] str;
    return;
}

 

posted @ 2015-08-26 09:38  VitalMa  阅读(2425)  评论(0编辑  收藏  举报