1. 程式人生 > >vc utf8與gb2312互相轉換.

vc utf8與gb2312互相轉換.

網上找到的版本大都是用CString轉換的那個.估計是在vc6代寫的東西.根本用不了.不過本人也是懶人.不想費那個事.這裡找到了另一個版本.其實應該叫做c++ utf8與gb2312互相轉換才對.

//UTF-8到GB2312的轉換
char* U2G(const char* utf8)
{
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);
if(wstr) delete[] wstr;
return str;
}

//GB2312到UTF-8的轉換
char* G2U(const char* gb2312)
{
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);
if(wstr) delete[] wstr;
return str;
}

無論是GB2312到UTF-8的轉換,還是UTF-8到GB2312的轉換,都需要注意的是在使用字串後,需要刪除字串指標;這是因為以上兩個方法返回的是字串指標,如果沒有刪除將會記憶體洩漏,可別說我沒提醒你哦。