首页 > 代码库 > 1.字符转换
1.字符转换
1、将单字节Char转化为双字节的wchar_t的转换函数
wchar_t* c2w(const char *str)
{
int length = strlen(str)+1;
wchar_t *t = (wchar_t*)malloc(sizeof(wchar_t)*length);
memset(t,0,length*sizeof(wchar_t));
MultiByteToWideChar(CP_ACP,0,str,strlen(str),t,length);
return t;
}
//将单字节char*转化为宽字节wchar_t*
wchar_t* AnsiToUnicode( const char* szStr )
{
int nLen = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szStr, -1, NULL, 0 );
if (nLen == 0)
{
return NULL;
}
wchar_t* pResult = new wchar_t[nLen];
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szStr, -1, pResult, nLen );
return pResult;
}
//将宽字节wchar_t*转化为单字节char*
inline char* UnicodeToAnsi( const wchar_t* szStr )
{
int nLen = WideCharToMultiByte( CP_ACP, 0, szStr, -1, NULL, 0, NULL, NULL );
if (nLen == 0)
{
return NULL;
}
char* pResult = new char[nLen];
WideCharToMultiByte( CP_ACP, 0, szStr, -1, pResult, nLen, NULL, NULL );
return pResult;
}
2、char[] 转换为 LPWSTR
解决方案:
思路一:
使用CA2W字符转换宏(ATL and MFC String Conversion Macros)。
根据MSDN描述,这个宏用于将ANSI转换为Wide Character(UNICODE)
代码如下:
LPWSTR aaa = CA2W(text);
item.pszText = aaa;
思路二:
使用int MultiByteToWideChar()函数。根据MSDN描述,这个方法:This
function maps a character string to a wide-character (Unicode)
string。
代码如下:
TCHAR aaa[31];
MultiByteToWideChar(0,0,text,31,aaa,62);
1.字符转换