C/C++ UTF8转ANSI字符串

时间:2023-01-10 20:40:12

C/C++ UTF8转ANSI字符串

步骤:UTF8先转UNICODE,再由UNICODE转ANSI字符串

//UTF8转ANSI字符串(OK,New)
char* STR::Utf8ToAnsi(char* utf8,int len,char szcc)
{
BOOL szok = FALSE;
int szlen = 0;
char* szretstr = NULL;
wchar_t* whar_str = NULL;
//UTF8转UNICODE
szlen = MultiByteToWideChar(CP_UTF8, 0, utf8, len, NULL, 0);
if (szlen <= 0)
goto Err;
szlen += 1;
whar_str = new wchar_t[szlen];
if (!whar_str)
goto Err;
ZeroMemory(whar_str, szlen * sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0, utf8, len, whar_str, szlen);
if (GetLastError() != 0)
goto Err;
//UNICODE转ANSI
szlen = WideCharToMultiByte(CP_ACP, 0, whar_str, len, NULL, 0,&szcc,&szok);
if (szlen <= 0)
goto Err;
szlen += 1;
szretstr = new char[szlen];
if (!szretstr)
goto Err;
ZeroMemory(szretstr, szlen * sizeof(char));
WideCharToMultiByte(CP_ACP, 0, whar_str, len, szretstr, szlen, &szcc, &szok);
if (GetLastError() != 0)
goto Err;
if (whar_str)
{
delete[] whar_str;
whar_str = NULL;
}
return szretstr;
Err:
if (whar_str)
{
delete[]whar_str;
whar_str = NULL;
}
return NULL;
}