您的位置:首页 > 其它

Unicode和ANSI之间转换 - U2A/A2U轻松实现

2013-04-02 14:35 316 查看

上一篇博客中描述了如何用NotePad++来实现Unicode ANSI之间的转换,这一篇中,我们将学习使用封装后的方法 U2A和A2U 来实现,具体代码如下:

#ifndef UNICODEANSI_H_
#define UNICODEANSI_H_

#define CP_JP  932
#define CP_CH  936
#define CP_KO  949
#define CP_RU  1251
#define CP_EU  1252  // ENGLISH, FRENCH, GERMAN, ITALIAN, PORTUGUESE, SPANISH

class CUnicodeAnsi
{
public:
// UNICODE -> ANSI
static LPSTR U2A(LPCWSTR wStr, int iCodePage)
{
// Get ANSI string length.
int iLen = ::WideCharToMultiByte(iCodePage, 0, wStr, -1, NULL, 0, NULL, NULL);
if( 0 > iLen ) return NULL;

char* aStr = new char[iLen];

// Convert Unicode to ANSI.
int tmpLen = ::WideCharToMultiByte(iCodePage, 0, wStr, -1, aStr, iLen, NULL, NULL);
if( 0 > tmpLen ) return NULL;

return aStr;
}

// ANSI -> UNICODE
static LPCWSTR A2U(LPCSTR aStr, int iCodePage)
{
// Get Unicode string length.
int iLen = ::MultiByteToWideChar(iCodePage, 0, aStr, -1, NULL, 0);
if( 0 > iLen ) return NULL;

wchar_t* uStr = new wchar_t[iLen];

// Convert ANSI to Unicode.
int tmpLen = ::MultiByteToWideChar(iCodePage, 0, aStr, -1, uStr, iLen);
if( 0 > tmpLen ) return NULL;

return uStr;
}
};

#endif // UNICODEANSI_H_

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: