Unicode环境下宽字符------->窄字符的转换
定义:TCHAR m_szIp[MAX_IP_LEN]; 我们要将TCHANR类型数组(宽字符型)转换为char*pBuffer类型(窄字符型):
方法一:
- int nNum=WideCharToMultiByte(CP_ACP,0,m_szIp,-1,0,0,NULL,NULL);
- char* pBuffer=new char[nNum+1];
- WideCharToMultiByte(CP_ACP,0,m_szIp,-1,pBuffer,nNum,NULL,NULL);
int nNum=WideCharToMultiByte(CP_ACP,0,m_szIp,-1,0,0,NULL,NULL);
char* pBuffer=new char[nNum+1];
WideCharToMultiByte(CP_ACP,0,m_szIp,-1,pBuffer,nNum,NULL,NULL);
方法二:T2A 、W2A
- USES_CONVERSION;
- char *pBuffer = T2A(m_szIp);
USES_CONVERSION;
char *pBuffer = T2A(m_szIp);
相反,同样情况下,窄字符--------->宽字符转换:
方法一:MultiByteToWideChar
方法二:A2T、A2W
下面是对方法一的两个函数的封装:
- char *WideCharToAnsi(wchar_t *pWideChar)
- {
- if (!pWideChar) return NULL;
- char *pszBuf = NULL;
- int needBytes = WideCharToMultiByte(CP_ACP, 0, pWideChar, -1, NULL, 0, NULL, NULL);
- if (needBytes > 0){
- pszBuf = new char[needBytes+1];
- ZeroMemory(pszBuf, (needBytes+1)*sizeof(char));
- WideCharToMultiByte(CP_ACP, 0, pWideChar, -1, pszBuf, needBytes, NULL, NULL);
- }
- return pszBuf;
- }
- wchar_t *AnsiCharToWide(char *pChar)
- {
- if (!pChar) return NULL;
- wchar_t *pszBuf = NULL;
- int needWChar = MultiByteToWideChar(CP_ACP, 0, pChar, -1, NULL, 0);
- if (needWChar > 0){
- pszBuf = new wchar_t[needWChar+1];
- ZeroMemory(pszBuf, (needWChar+1)*sizeof(wchar_t));
- MultiByteToWideChar(CP_ACP, 0, pChar, -1, pszBuf, needWChar);
- }
- return pszBuf;
- }
char *WideCharToAnsi(wchar_t *pWideChar)
{
if (!pWideChar) return NULL;
char *pszBuf = NULL;
int needBytes = WideCharToMultiByte(CP_ACP, 0, pWideChar, -1, NULL, 0, NULL, NULL);
if (needBytes > 0){
pszBuf = new char[needBytes+1];
ZeroMemory(pszBuf, (needBytes+1)*sizeof(char));
WideCharToMultiByte(CP_ACP, 0, pWideChar, -1, pszBuf, needBytes, NULL, NULL);
}
return pszBuf;
}
wchar_t *AnsiCharToWide(char *pChar)
{
if (!pChar) return NULL;
wchar_t *pszBuf = NULL;
int needWChar = MultiByteToWideChar(CP_ACP, 0, pChar, -1, NULL, 0);
if (needWChar > 0){
pszBuf = new wchar_t[needWChar+1];
ZeroMemory(pszBuf, (needWChar+1)*sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0, pChar, -1, pszBuf, needWChar);
}
return pszBuf;
}