- 论坛徽章:
- 0
|
int gbk2utf8(char *utfStr,const char *srcStr,int maxUtfStrlen)
{
if(NULL==srcStr)
{
printf("Bad Parameter\n");
return -1;
}
//首先先将gbk编码转换为unicode编码
if(NULL==setlocale(LC_ALL,"zh_CN.gbk"))//设置转换为unicode前的码,当前为gbk编码
{
printf("Bad Parameter\n");
return -1;
}
int unicodeLen=mbstowcs(NULL,srcStr,0);//计算转换后的长度
if(unicodeLen<=0)
{
printf("Can not Transfer!!!\n");
return -1;
}
wchar_t *unicodeStr=(wchar_t *)calloc(sizeof(wchar_t),unicodeLen+1);
mbstowcs(unicodeStr,srcStr,strlen(srcStr));//将gbk转换为unicode
//将unicode编码转换为utf8编码
if(NULL==setlocale(LC_ALL,"zh_CN.utf8"))//设置unicode转换后的码,当前为utf8
{
printf("Bad Parameter\n");
return -1;
}
int utfLen=wcstombs(NULL,unicodeStr,0);//计算转换后的长度
if(utfLen<=0)
{
printf("Can not Transfer!!!\n");
return -1;
}
else if(utfLen>=maxUtfStrlen)//判断空间是否足够
{
printf("Dst Str memory not enough\n");
return -1;
}
wcstombs(utfStr,unicodeStr,utfLen);
utfStr[utfLen]=0;//添加结束符
free(unicodeStr);
return utfLen;
}
|
|