1. unicode宽字符至多字符的转换
char *w2c(char *pcstr,const wchar_t *pwstr, size_t len)
{
int nLength=wcslen(pwstr);
//获取转换后的长度
int nBytes = WideCharToMultiByte( // Bytes required for "hello" is 5, does not include null terminator
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 );
// make sure the buffer is big enough for this, making it larger if necessary
if(nBytes>len)nBytes=len;
// 通过以上得到的结果,转换unicode 字符为ascii 字符
WideCharToMultiByte( // Writes 5 bytes "hello", does not write a null terminator after that
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 );
return pcstr ;
}
2. 把asii字符转换为unicode字符,和上面相同的原理
void c2w(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;
}
}
本文提供了两个实用函数:一个用于将Unicode宽字符转换为ASCII字符,另一个用于将ASCII字符转换为Unicode宽字符。通过示例代码详细展示了如何使用Windows API中的WideCharToMultiByte和MultiByteToWideChar函数实现这两种转换。
1519

被折叠的 条评论
为什么被折叠?



