char 转wchar_t 及wchar_t转char
来源:互联网 发布:网络英语教程 编辑:程序博客网 时间:2024/05/22 13:21
char 转wchar_t 及wchar_t转char
原文来自http://haofu123.blog.163.com/blog/static/178294920096243161997/
利用widechartomultibyte来转换的函数
通常适合于window平台上使用
#include
#include
int_tmain(int argc, _tchar* argv[])
{
wchar_tpwstr[] =l"我是中国人";
wchar_tpwstr2[20];
char *pcstr = (char *)malloc(sizeof(char)*(2 * wcslen(pwstr)+1));
memset(pcstr , 0 , 2 * wcslen(pwstr)+1 );
w2c(pcstr,pwstr,2 * wcslen(pwstr)+1) ;
printf("%s\n",pcstr);
c2w(pwstr2,20,pcstr);
wprintf(l"%s",pwstr2);
free(pcstr) ;
return0;
}
//将wchar_t*转成char*的实现函数如下:
char*w2c(char *pcstr,const wchar_t *pwstr, size_t len)
{
intnlength=wcslen(pwstr);
//获取转换后的长度
intnbytes = WideCharToMultiByte( 0, // specify the code page used to perform the conversion
0, // no special flags to handle unmapped characters
pwstr, // wide character string to convert
nlength, // the number of wide characters in that string
NULL, // no output buffer given, we just want to know how long it needs to be
0,
NULL, // no replacement character given
NULL); // we don't want to know if a character didn't make it through the translation
// make sure the buffer is big enough for this, making it larger if necessary
if(nbytes>len) nbytes=len;
//通过以上得到的结果,转换unicode 字符为ascii 字符
WideCharToMultiByte(0, // specify the code page used to perform the conversion
0, // no special flags to handle unmapped characters
pwstr, // wide character string to convert
nlength, // the number of wide characters in that string
pcstr,// put the output ascii characters at the end of the buffer
nbytes, // there is at least this much space there
NULL, // no replacement character given
NULL);
returnpcstr ;
}
//将char*转成wchar_t*的实现函数如下:
//这是把asii字符转换为unicode字符,和上面相同的原理
voidc2w(wchar_t *pwstr,size_t len,const char *str)
{
if(str)
{
size_t nu = strlen(str);
size_t n =(size_t)multibytetowidechar(cp_acp,0,(const char *)str,(int)nu,null,0);
if(n>=len)n=len-1;
multibytetowidechar(cp_acp,0,(const char *)str,(int)nu,pwstr,(int)n);
pwstr[n]=0;
}
}
或者用此种方法更好一些:============我自已做的
//把ascii字符转换为unicode字符
wchar_t*Cphone_hq::ctow(wchar_t *pwstr, const char *str)
{
wchar_t*buffer;
if(str)
{
size_t nu = strlen(str);
size_t n =(size_t)MultiByteToWideChar(CP_ACP,0,(const char *)str,int(nu),NULL,0);
buffer=0;
buffer = new wchar_t[n+1];
#include
int
{
wchar_t
wchar_t
c2w(pwstr2,20,pcstr);
wprintf(l"%s",pwstr2);
return
}
//将wchar_t*
char
{
int
//获取转换后的长度
int
0,
pwstr,
nlength,
NULL,
0,
NULL,
NULL
if(nbytes>len)
//
WideCharToMultiByte(
0,
pwstr,
nlength,
pcstr,
nbytes,
NULL,
NULL
return
}
//将char*
void
{
if(str)
}
或者用此种方法更好一些:============我自已做的
//把ascii
wchar_t*
{
wchar_t*
if(str)