Unicode和ANSI之间转换 - U2A/A2U轻松实现
上一篇博客中描述了如何用NotePad++来实现Unicode ANSI之间的转换,这一篇中,我们将学习使用封装后的方法 U2A和A2U 来实现,具体代码如下:
1 #ifndef UNICODEANSI_H_ 2 #define UNICODEANSI_H_ 3 4 #define CP_JP 932 5 #define CP_CH 936 6 #define CP_KO 949 7 #define CP_RU 1251 8 #define CP_EU 1252 // ENGLISH, FRENCH, GERMAN, ITALIAN, PORTUGUESE, SPANISH 9 10 class CUnicodeAnsi 11 { 12 public: 13 // UNICODE -> ANSI 14 static LPSTR U2A(LPCWSTR wStr, int iCodePage) 15 { 16 // Get ANSI string length. 17 int iLen = ::WideCharToMultiByte(iCodePage, 0, wStr, -1, NULL, 0, NULL, NULL); 18 if( 0 > iLen ) return NULL; 19 20 char* aStr = new char[iLen]; 21 22 // Convert Unicode to ANSI. 23 int tmpLen = ::WideCharToMultiByte(iCodePage, 0, wStr, -1, aStr, iLen, NULL, NULL); 24 if( 0 > tmpLen ) return NULL; 25 26 return aStr; 27 } 28 29 // ANSI -> UNICODE 30 static LPCWSTR A2U(LPCSTR aStr, int iCodePage) 31 { 32 // Get Unicode string length. 33 int iLen = ::MultiByteToWideChar(iCodePage, 0, aStr, -1, NULL, 0); 34 if( 0 > iLen ) return NULL; 35 36 wchar_t* uStr = new wchar_t[iLen]; 37 38 // Convert ANSI to Unicode. 39 int tmpLen = ::MultiByteToWideChar(iCodePage, 0, aStr, -1, uStr, iLen); 40 if( 0 > tmpLen ) return NULL; 41 42 return uStr; 43 } 44 }; 45 46 #endif // UNICODEANSI_H_