WideCharToMultiByte 和 MultiByteToWideChar 详解

来源:互联网 发布:淘宝软件 编辑:程序博客网 时间:2024/05/22 13:33

 WideCharToMultiByte 和 MultiByteToWideChar 两个函数的使用详解
// Unicode转char *(宽字节转多字节)TCHAR strWideChar[] = _T("zerosoul");   //Unicode宽字节编码字符串strWideChar  //获得转换后的字符串长度n_len  int n_len = WideCharToMultiByte(CP_ACP, NULL, strWideChar, -1, NULL, 0, NULL, NULL);  char* strMultiByte = new char[n_len];   //ANSI多字节编码字符串strMultiByte  WideCharToMultiByte(CP_ACP, NULL, strWideChar, -1, strMultiByte, n_len, NULL, NULL);  //开始转换  printf("strMultiByte : %s\n",strMultiByte);   // char *转Unicode(多字节转宽字节) char strMultiByte[] = "zerosoul";   //ANSI多字节编码字符串strMultiByte  //获得转换后的字符串长度n_len  int n_len = MultiByteToWideChar(CP_ACP,NULL,strMultiByte,-1,NULL,0);  TCHAR* strWideChar = new TCHAR[n_len];  //Unicode宽字节编码字符串strWideChar  MultiByteToWideChar(CP_ACP,NULL,strMultiByte,-1,strWideChar,n_len); //开始转换  _tprintf(_T("strWideChar : %s\n"),strWideChar);


// Convert a C string in UTF-8 format to Unicode format.void UTF8ToUnicode(LPTSTR pcOut, int nOutLen, const char* kpcIn){MultiByteToWideChar(CP_UTF8, 0, kpcIn, -1, pcOut, nOutLen);}// Convert a Unicode string to C string in UTF-8 format.void UnicodeToUTF8(char* pcOut, int nOutLen, LPCWSTR kpcIn){WideCharToMultiByte(CP_UTF8, 0, kpcIn, -1, pcOut, nOutLen, 0, 0);}// Convert a Unicode string to C string in ANSI format.void UnicodeToANSI(char* pcOut, int nOutLen, LPCWSTR kpcIn){WideCharToMultiByte(CP_ACP, 0, kpcIn, -1, pcOut, nOutLen, 0, 0);}// Convert a C string in ANSI format to Unicode format.void ANSIToUnicode(LPTSTR pcOut, int nOutLen, const char* kpcIn){MultiByteToWideChar(CP_ACP, 0, kpcIn, -1, pcOut, nOutLen);}

函数原型:int WideCharToMultiByte(  __in   UINT CodePage,  __in   DWORD dwFlags,  __in   LPCWSTR lpWideCharStr,  __in   int cchWideChar,  __out  LPSTR lpMultiByteStr,  __in   int cbMultiByte,  __in   LPCSTR lpDefaultChar,  __out  LPBOOL lpUsedDefaultChar);int MultiByteToWideChar(  __in   UINT CodePage,  __in   DWORD dwFlags,  __in   LPCSTR lpMultiByteStr,  __in   int cbMultiByte,  __out  LPWSTR lpWideCharStr,  __in   int cchWideChar);

参数:CodePage: 指定要转换成的字符集代码页,它可以是任何已经安装的或系统自带的字符集,你也可以使用如下所示代码页之一。CP_ACP 当前系统ANSI代码页 CP_MACCP 当前系统Macintosh代码页 CP_OEMCP 当前系统OEM代码页,一种原始设备制造商硬件扫描码 CP_SYMBOL Symbol代码页,用于Windows 2000及以后版本,我不明白是什么CP_THREAD_ACP 当前线程ANSI代码页,用于Windows 2000及以后版本,我不明白是什么 CP_UTF7 UTF-7,设置此值时lpDefaultChar和lpUsedDefaultChar都必须为NULLCP_UTF8 UTF-8,设置此值时lpDefaultChar和lpUsedDefaultChar都必须为NULL最常用的是CP_ACP和CP_UTF8了,前者将宽字符转换为ANSI,后者转换为UTF8。

浅谈文字编码和Unicode(上)

浅谈文字编码和Unicode(下)



原创粉丝点击