在UTF-8,与UNICODE之间转换的时候,用二进制运算,代替了字符串的转换。UTF-8一个汉字,用3个字节,而UNICODE用2个字节;对应关系如下:
1.UTF-8编码:
2.[1,1,1,0,A5,A6,A7,A8], [1,0,B3,B4,B5,B6,B7,B8],
3.[1,0,C3,C4,C5,C6,C7,C8];
对应的UNICODE编码:
1.[A5,A6,A7,A8,B3,B4,B5,B6],
2.[B7,B8,C3,C4,C5,C6,C7,C8]
因此我们只需进行位操作,即可达到目的;如:
01.// 把UTF-8转换成Unicode
02.void CChineseCodeLib::UTF_8ToUnicode(WCHAR* pOut,char*pText)
03.{
04.char* uchar = (char*)pOut;
05.
06.uchar[1] = ((pText[0] & 0x0F) << 4) + ((pText[1] >> 2) & 0x0F);
07.uchar[0] = ((pText[1] & 0x03) << 6) + (pText[2] & 0x3F);
08.
10.}
01.// Unicode 转换成UTF-8
02.void CChineseCodeLib::UnicodeToUTF_8(char* pOut,WCHAR* pText)
03.{
04.// 注意 WCHAR高低字的顺序,低字节在前,高字节在后
05.char* pchar = (char*)pText;
06.
07.pOut[0] = (0xE0 | ((pchar[1] & 0xF0) >> 4));
08.pOut[1] = (0x80 | ((pchar[1] & 0x0F) << 2)) + ((pchar[0] & 0xC0) >> 6);
09.pOut[2] = (0x80 | (pchar[0] & 0x3F));
10.
12.}
1.// 把Unicode 转换成 GB2312
2.void CChineseCodeLib::UnicodeToGB2312(char*
pOut,unsigned short uData)
3.{
4.WideCharToMultiByte(CP_ACP,NULL,&uData,1,pOut,sizeof(WCHAR),NULL,NU LL);
6.}
1.// GB2312 转换成Unicode
2.void CChineseCodeLib::Gb2312ToUnicode(WCHAR* pOut,char*gbBuffer)
3.{
4.::MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,gbBuffer,2,pOut,1);
6.}
01.//GB2312 转为 UTF-8
02.void CChineseCodeLib::GB2312ToUTF_8(string&
pOut,char*pText, int pLen)
03.{
04.char buf[4];
05.char* rst = new char[pLen + (pLen >> 2) + 2];
06.
09.
10.int i = 0;
11.int j = 0;
12.while(i < pLen)
13.{
14.//如果是英文直接复制就可以
15.if( *(pText + i) >= 0)
16.{
17.rst[j++] = pText[i++];
18.}
19.else
20.{
21.WCHAR pbuffer;
22.Gb2312ToUnicode(&pbuffer,pText+i);
23.
24.UnicodeToUTF_8(buf,&pbuffer);
25.
26.unsigned short int tmp = 0;
30.unicode编码转换二进制
31.
32.j += 3;
33.i += 2;
34.}
35.}
36.rst[j] = ''\0'';
37.
38.//返回结果
39.pOut = rst;
40.delete[]rst;
41.
43.}
01.//UTF-8 转为 GB2312
02.void CChineseCodeLib::UTF_8ToGB2312(string &pOut, char*pText, int pLen)
03.{
04.char* newBuf = new char[pLen];
05.char Ctemp[4];
07.
08.int i =0;
09.int j = 0;
10.
11.while(i < pLen)
12.{
13.if(pText[i] > 0)
14.{
pText[i++];
16.}
17.else
18.{
19.WCHAR Wtemp;
20.UTF_8ToUnicode(&Wtemp,pText + i);
21.
22.UnicodeToGB2312(Ctemp,Wtemp);
23.
26.
27.i += 3;
28.j += 2;
29.}
30.}
32.
33.pOut = newBuf;
34.delete[]newBuf;
35.
37.}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论