UTF8 ANSI 相互转换的函数

#include <winnls.h> #include <malloc.h> LPCSTR AnsiToUtf8(LPCSTR Ansi) { int WLength = MultiByteToWideChar(CP_ACP, 0, Ansi, -1, NULL, 0); LPWSTR pszW = (LPWSTR) _alloca((WLength+1) * sizeof(WCHAR)); MultiByteToWideChar(CP_ACP, 0, Ansi, -1, pszW, WLength); int ALength = WideCharToMultiByte(CP_UTF8, 0, pszW, -1, NULL, 0, NULL, NULL); LPSTR pszA = (LPSTR)_alloca( ALength + 1); WideCharToMultiByte(CP_UTF8, 0, pszW, -1, pszA, ALength, NULL, NULL); pszA[ALength] = 0; return pszA; } LPCSTR WcharToUtf8(LPCWSTR szUnicode) { int ALength = WideCharToMultiByte(CP_UTF8, 0, szUnicode, -1, NULL, 0, NULL, NULL); LPSTR pszA = (LPSTR)_alloca( ALength + 1); WideCharToMultiByte(CP_UTF8, 0, szUnicode, -1, pszA, ALength, NULL, NULL); pszA[ALength] = 0; return pszA; } LPCSTR Utf8toAnsi( LPCSTR utf8 ) { int WLength = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, NULL ); LPWSTR pszW = (LPWSTR) _alloca( (WLength + 1) *sizeof(WCHAR) ) ; MultiByteToWideChar(CP_UTF8, 0, utf8, -1, pszW, WLength ); pszW[WLength] = 0; int ALength = WideCharToMultiByte(CP_ACP, 0, pszW, -1, NULL, 0, NULL, NULL); LPSTR pszA = ( LPSTR ) _alloca ( ALength + 1 ); WideCharToMultiByte(CP_ACP, 0, pszW, -1, pszA, ALength, NULL, NULL); pszA[ALength] = 0; return pszA; } LPCWSTR Utf8toWchar( LPCSTR utf8 ) { int WLength = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, NULL ); LPWSTR pszW = (LPWSTR) _alloca( (WLength + 1) *sizeof(WCHAR) ) ; MultiByteToWideChar(CP_UTF8, 0, utf8, -1, pszW, WLength ); pszW[WLength] = 0; return pszW; }

 

 

//测试代码 TCHAR szBuf[1204] = { "我是中国人" }; TRACE("%s/n", szBuf); strcpy( szBuf, AnsiToUtf8( szBuf )); TRACE("%s/n", szBuf); strcpy( szBuf, Utf8toAnsi(szBuf)); TRACE("%s/n", szBuf); strcpy( szBuf, "浣犳槸鎴戠殑濂芥湅鍙嬪悧"); TRACE("%s/n", szBuf); strcpy( szBuf, Utf8toAnsi( szBuf ) ); TRACE("%s/n", szBuf ); strcpy( szBuf, AnsiToUtf8( szBuf ) ); TRACE("%s/n", szBuf );

调试输出

我是中国人 (CE D2 CA C7 D6 D0 B9 FA C8 CB 00)

鎴戞槸涓浗浜?  (E6 88 91 E6 98 AF E4 B8 AD E5 9B BD E4 BA BA 00)

我是中国人 (CE D2 CA C7 D6 D0 B9 FA C8 CB 00)

浣犳槸鎴戠殑濂芥湅鍙嬪悧 (E4 BD A0 E6 98 AF E6 88 91 E7 9A 84 E5 A5 BD E6 9C 8B E5 8F 8B E5 90 97 00)

你是我的好朋友吗 (C4 E3 CA C7 CE D2 B5 C4 BA C3 C5 F3 D3 D1 C2 F0 00 )

浣犳槸鎴戠殑濂芥湅鍙嬪悧 (E4 BD A0 E6 98 AF E6 88 91 E7 9A 84 E5 A5 BD E6 9C 8B E5 8F 8B E5 90 97 00)

你可能感兴趣的:(c,测试,null,include)