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_

 

转载于:https://www.cnblogs.com/nchxmoon/archive/2013/04/02/2995474.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值