关闭

C语言下Unicode字符串与多字节字符串转换方法

1078人阅读 评论(0) 收藏 举报
分类:

1.Unicode字符串转换为多字节字符串:

size_t wlen = 0;
wchar_t *wstr = (wchar_t*)pSrc; //source unicode string
size_t byteLen =0; //unicode string length in byte 
size_t coverted = 0;
char retBuf[MODEL_CODEC_MAX_VALUE_LEN];
ST_RET ret = SD_FAILURE;


setlocale(LC_ALL,"chs");//setlocale(LC_ALL,"chs")会改变整个应用程序的字符集编码方式,调用完之后使用 //setlocale(LC_ALL,"C")还原。
wlen = wcslen(wstr);
byteLen = wlen * 2 + 1;

memset(retBuf,0,MODEL_CODEC_MAX_VALUE_LEN);
if(0 != wcstombs_s(&coverted,retBuf,MODEL_CODEC_MAX_VALUE_LEN,wstr,_TRUNCATE))
{
ret = SD_FAILURE;
}
else
{
ret = SD_SUCCESS;
}
setlocale(LC_ALL,"C");
assert(strlen(retBuf) < MODEL_CODEC_MAX_VALUE_LEN);
if(ret == SD_SUCCESS)
{
if(0 != strncpy_s(text,MODEL_CODEC_MAX_VALUE_LEN,retBuf,MODEL_CODEC_MAX_VALUE_LEN))
{
ret = SD_FAILURE;
}
}
return ret;

2.多字节字符串转换为Unicode字符串

setlocale(LC_ALL,"chs");
size_t len = strlen(text);
size_t converted = 0;
const int retLen = 512/sizeof(wchar_t);
wchar_t *retBuf = new wchar_t[retLen];
memset(retBuf,0,retLen);
bool ret = false;
if (0 != mbstowcs_s(&converted,retBuf,retLen,str,_TRUNCATE))
{
ret = false;
}
else
{
ret = true;
}
setlocale(LC_ALL,"C");
if (ret == true)
{
if (0 != wcsncpy_s(wstr,wcslen(retBuf)+1,retBuf,wcslen(retBuf)))
{
ret = false;
}
}
delete [] retBuf;
retBuf = 0;
return ret;

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:140116次
    • 积分:1955
    • 等级:
    • 排名:千里之外
    • 原创:46篇
    • 转载:80篇
    • 译文:0篇
    • 评论:15条
    最新评论