C++中文转码问题(GB2312 -> UTF8)

 //GB to utf-8
void udmsEntrance::GB2312ToUTF_8(string& pOut,const char *pText, int pLen) { 
char buf[4]; 
memset(buf,0,4); 
pOut.clear(); 
int i = 0; 
while(i < pLen) { 
//copy directly if it is a english char
if( pText[i] >= 0){ 
char asciistr[2]={0}; 
asciistr[0] = (pText[i++]); 
pOut.append(asciistr); 
}else { 
WCHAR pbuffer; 
Gb2312ToUnicode(&pbuffer,pText+i); 
UnicodeToUTF_8(buf,&pbuffer); 
pOut.append(buf); 
i += 2; 


return; 


void udmsEntrance::Gb2312ToUnicode(WCHAR* pOut,const char *gbBuffer){ 
MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,gbBuffer,2,pOut,1); 
return; 
}

void udmsEntrance::UnicodeToUTF_8(char* pOut,WCHAR* pText){ 
char* pchar = (char *)pText; 
pOut[0] = (0xE0 | ((pchar[1] & 0xF0) >> 4)); 
pOut[1] = (0x80 | ((pchar[1] & 0x0F) << 2)) + ((pchar[0] & 0xC0) >> 6); 
pOut[2] = (0x80 | (pchar[0] & 0x3F)); 
return; 

void udmsEntrance::UTF_8ToGB2312(string &pOut, const char *pText, int pLen){ 
char buf[4]; 
char* rst = new char[pLen + (pLen >> 2) + 2]; 
memset(buf,0,4); 
memset(rst,0,pLen + (pLen >> 2) + 2); 
int i =0; 
int j = 0; 
while(i < pLen){ 
if(*(pText + i) >= 0){ 
rst[j++] = pText[i++]; 
}else{ 
WCHAR Wtemp; 
UTF_8ToUnicode(&Wtemp,pText + i); 
UnicodeToGB2312(buf,Wtemp); 
unsigned short int tmp = 0; 
tmp = rst[j] = buf[0]; 
tmp = rst[j+1] = buf[1]; 
tmp = rst[j+2] = buf[2]; 
i += 3; 
j += 2; 


rst[j]='\0'; 
pOut = rst; 
delete []rst; 


void udmsEntrance::UTF_8ToUnicode(WCHAR* pOut,const char *pText) { 
char* uchar = (char *)pOut; 
uchar[1] = ((pText[0] & 0x0F) << 4) + ((pText[1] >> 2) & 0x0F); 
uchar[0] = ((pText[1] & 0x03) << 6) + (pText[2] & 0x3F); 
return; 


void udmsEntrance::UnicodeToGB2312(char* pOut,WCHAR uData){ 
WideCharToMultiByte(CP_ACP,NULL,&uData,1,pOut,sizeof(WCHAR),NULL,NULL); 
return; 

转载于:https://my.oschina.net/liangxiao/blog/118182

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值