如何把UTF-8转为GB2312的

时间:2021-02-20 22:20:56
目前很多的中文网页都采用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;
}