昨天發布的http協議嗅探插件源碼,里面有UTF-8轉GB2312的一個函數BOOL UTF8_2_GB2312(const void * pIn,int inLen,char *pOut,int *outLen ),這里介紹下。
目前很多的中文網頁都采用UTF-8或GB2312編碼,UTF-8和GB2312都是字符集的編碼,具體格式這里不做討論,這里主要是看看如何用把UTF-8轉為GB2312的。在vc的開發平臺里UTF-8漢字會顯示成亂碼,需要轉換成GB2312才能顯示。
大概的思路是這樣的,先把UTF8轉換成UNICODE,再把UNICODE轉換成GB2312,為什么會這樣想呢,因為windows
API里提供了多字節轉寬字節(MultiByteToWideChar),寬字節轉多字節(WideCharToMultiByte)的方法。好了,下
面是具體的API使用:MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)pIn,inLen, pWchar,
len),第一個參數是CP_UTF8,這樣就把UTF8轉成UNICODE了。你再用WideCharToMultiByte就能把UNICODE轉成
GB2312了。
如果你是在MFC下,,直接用CString構造就能把UNICODE轉成GB2312,構造函數是有類型轉換功能滴。。。
函數源碼,VC6編譯通過:
BOOL UTF8_2_GB2312(const void * pIn,int inLen,char *pOut,int *outLen )
{
ASSERT( ( (NULL==pIn) ||( NULL==pOut) ) );
int len=MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)pIn, -1, NULL,0);
wchar_t *pWchar = new wchar_t[len+1];
if (NULL==pWchar)
return FALSE;
memset(pWchar,0,(len+1)* sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)pIn,inLen, pWchar, len);
CString str=CString(pWchar);
ASSERT(str.GetLength()>(*outLen));//not enough output buff
*outLen = str.GetLength();
memcpy(pOut,str.GetBuffer(0),*outLen);
delete[]pWchar;
return TRUE;
}