MultiByteToWideChar和WideCharToMultiByte
在软件的使用过程中,经常碰到乱码的情况,那么乱码的原因就是字符集的不同,也就是说同一个数字代表不同意思。在Windows里,目前主要有ANSI和UNICODE的方式。如果在UNICODE的方式里直接显示ANSI的字符串是出现乱码的,同样在ANSI函数里也不能显示UNICODE的字符串,而是要进行相互转换才能显示正确的字符串。在NT以后的操作系统里,
Windows底层函数已经全部改为UNICODE的方式,如果还是使用ANSI的话,要比UNICODE函数慢一些,
系统底层会从ANSI的方式转换为UNICODE方式,然后再显示出来。从ANSI转换为UNICODE的字符串,就可以使用函数MultiByteToWideChar来实现。
函数MultiByteToWideChar声明如下:
1
2
3
4
5
6
7
8
9
10
|
WINBASEAPI
int
WINAPI
MultiByteToWideChar(
__in UINT CodePage,
__in DWORD dwFlags,
__in LPCSTR lpMultiByteStr,
__in int cbMultiByte,
__out_ecount_opt(cchWideChar) LPWSTR lpWideCharStr,
__in int cchWideChar);
|
CodePage是代码表。//常用的代码页由CP_ACP和CP_UTF8两个。CP_ACP实了ANSI与Unicode之间的转换。CP_UTF8代码页实现UTF-8与Unicode之间的转换。
dwFlags是转换标志。
lpMultiByteStr是输入ANSI字符串。
cbMultiByte是输入ANSI的字符串长度。//为-1时,表示该字符串是以NULL结尾的字符串,其长度会自动计入字符串长度之内,
lpWideCharStr是输出UNICODE字符串。
cchWideChar是输出UNICODE字符串的缓冲区大小。//如果该值为0,函数返回值为需要的宽字符字节大小
下面是代码实现:
ANSI <--> Unicode <--> UTF8
wchar_t * ANSIToUnicode( const char* str )
{
}
/***********************************************************************/
void AnsiToUnicode(WCHAR *dst, const char *str)
{
if( str == NULL )
{
return;
}
int len = (int)strlen(str);
int nLen = MultiByteToWideChar(CP_ACP, 0,(char *)str, -1, NULL, NULL);
MultiByteToWideChar(CP_ACP, 0,(char *)str, len, dst, nLen);
dst[nLen-1] = 0;
}
/**********************************************************************/
char * UnicodeToANSI( const wchar_t *str )
{
}
wchar_t * UTF8ToUnicode( const char* str )
{
}
char * UnicodeToUTF8( const wchar_t *str )
{
}