ansi与utf8相互转换
#include <winnls.h>
#include <malloc.h>
LPCSTR AnsiToUtf8(LPCSTR Ansi)
{
int WLength = MultiByteToWideChar(CP_ACP, 0, Ansi, -1, NULL, 0);
LPWSTR pszW = (LPWSTR) _alloca((WLength+1) * sizeof(WCHAR));
MultiByteToWideChar(CP_ACP, 0, Ansi, -1, pszW, WLength);
int ALength = WideCharToMultiByte(CP_UTF8, 0, pszW, -1, NULL, 0, NULL, NULL);
LPSTR pszA = (LPSTR)_alloca( ALength + 1);
WideCharToMultiByte(CP_UTF8, 0, pszW, -1, pszA, ALength, NULL, NULL);
pszA[ALength] = 0;
return pszA;
}
LPCSTR WcharToUtf8(LPCWSTR szUnicode)
{
int ALength = WideCharToMultiByte(CP_UTF8, 0, szUnicode, -1, NULL, 0, NULL, NULL);
LPSTR pszA = (LPSTR)_alloca( ALength + 1);
WideCharToMultiByte(CP_UTF8, 0, szUnicode, -1, pszA, ALength, NULL, NULL);
pszA[ALength] = 0;
return pszA;
}
LPCSTR Utf8toAnsi( LPCSTR utf8 )
{
int WLength = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, NULL );
LPWSTR pszW = (LPWSTR) _alloca( (WLength + 1) *sizeof(WCHAR) ) ;
MultiByteToWideChar(CP_UTF8, 0, utf8, -1, pszW, WLength );
pszW[WLength] = 0;
int ALength = WideCharToMultiByte(CP_ACP, 0, pszW, -1, NULL, 0, NULL, NULL);
LPSTR pszA = ( LPSTR ) _alloca ( ALength + 1 );
WideCharToMultiByte(CP_ACP, 0, pszW, -1, pszA, ALength, NULL, NULL);
pszA[ALength] = 0;
return pszA;
}
LPCWSTR Utf8toWchar( LPCSTR utf8 )
{
int WLength = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, NULL );
LPWSTR pszW = (LPWSTR) _alloca( (WLength + 1) *sizeof(WCHAR) ) ;
MultiByteToWideChar(CP_UTF8, 0, utf8, -1, pszW, WLength );
pszW[WLength] = 0;
return pszW;
}
重新又调整了更安全的代码
CString ChangeStringCodePage(CString strTemp,UINT uSrcCodePage, UINT uDesCodePage)
{
CString strResult = strTemp;
DWORD dwBufSize = WideCharToMultiByte(uSrcCodePage, 0, strTemp, -1, NULL, 0, NULL, FALSE);
dwBufSize += 8;
char *pszBuf = new char[dwBufSize];
if (NULL == pszBuf)
{
//申请内存失败
return strResult;
}
memset(pszBuf, 0, dwBufSize);
if (0 == WideCharToMultiByte(uSrcCodePage, 0, strTemp,-1, pszBuf, dwBufSize, NULL, NULL))
{
delete []pszBuf;
pszBuf = NULL;
//宽字节转多字节失败
return strResult;
}
dwBufSize = MultiByteToWideChar(uDesCodePage, 0, pszBuf, -1, NULL, 0);
dwBufSize += 8;
TCHAR *pszPath = new TCHAR[dwBufSize];
if (NULL == pszPath)
{
//申请内存失败
return strResult;
}
memset(pszPath, 0, dwBufSize * sizeof(TCHAR));
if (0 == MultiByteToWideChar(uDesCodePage, 0, pszBuf, -1, pszPath, dwBufSize))
{
delete []pszBuf;
pszBuf = NULL;
delete []pszPath;
pszPath = NULL;
//多字节转宽字节失败
return strResult;
}
delete []pszBuf;
pszBuf = NULL;
strResult = pszPath;
delete []pszPath;
pszPath = NULL;
return strResult;
}
int main()
{
CString strRecv;
strRecv = ChangeStringCodePage(strRecv, CP_ACP, CP_UTF8);
}