//转码
//ASCII to Unicode
wstring AtoW(const std::string &str)
{
//unicode的长度
int nwLen = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, nullptr, 0);
//分配内存
wchar_t *pUnicode = (wchar_t *)malloc(sizeof(wchar_t) * nwLen);
if (pUnicode)
{
MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, pUnicode, nwLen);
wstring wstr = pUnicode;
free(pUnicode);
return wstr;
}
return NULL;
}
//Unicode to ASCII
std::string WtoA(const wstring &wstr)
{
int naLen = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
char *pAssii = (char *)malloc(sizeof(char) * naLen);
if (pAssii)
{
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, pAssii, naLen, nullptr, nullptr);
std::string str = pAssii;
free(pAssii);
return str;
}
return NULL;
}
//utf8 to Unicode
wstring U2W(const std::string &str)
{
int nwLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);
wchar_t *pUnicode = (wchar_t *)malloc(sizeof(wchar_t) * nwLen);
if (pUnicode)
{
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, pUnicode, nwLen);
wstring wstr = pUnicode;
free(pUnicode);
return wstr;
}
return NULL;
}
//Unicode to utf8
std::string W2U(const wstring &wstr)
{
int naLen = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
char *pAssii = (char *)malloc(sizeof(char) * naLen);
if (pAssii)
{
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, pAssii, naLen, nullptr, nullptr);
std::string str = pAssii;
free(pAssii);
return str;
}
return NULL;
}
//ASCII to utf8
string A2U(const std::string &str)
{
return W2U(AtoW(str));
}
//utf8 to ASCII
string U2A(const std::string &str)
{
return WtoA(U2W(str));
}