以下程序代码实现了UTF8到UTF-16的转换,同时将转换的数据保存到CString对象中
不废话,直接上代码:
bool UTF8ToCString(char utf8str[],CString *csout,int len)
{
int i,j,k;
unsigned char tempch,datach[6]={0};
unsigned long byteout;
int pos=0;
//cout<<"utf8str:";
//for(i=0;i<len;i++)printf("%02X ",(unsigned char)utf8str[i]);
cout<<endl;
i=0;
csout->Empty();
CString CStemp;
for(i=0;i<len-1;)
{
for(j=0;j<6;j++)datach[j]=0;
tempch=(unsigned char)utf8str[i];
j=0;
k=0;
while((tempch>>7)&0x01)
{
k++;
tempch=tempch<<1;
}
if(0==k)
{
CStemp.Format(_T("%c"),(unsigned char)utf8str[i]);
k=1;
}
else if(k<=6)
{
datach[0]=(unsigned char)utf8str[i]<<(1+k);
byteout=datach[0]>>(k+1);
for(j=1;j<k;j++)
{
datach[j]=utf8str[i+j]&0x3F;
byteout=(byteout<<6)|datach[j];
}
CStemp.Format(_T("%c"),byteout);
}
*csout+=CStemp;
i+=k;
}
return true;
}