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

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;

阅读更多
个人分类: C语言基础
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

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

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭