标签:
标准编解码函数
编码,当前默认编码转Utf-8
bool CodeToUtf8(const std::string &sSrc, std::string &sDst)
{
int iNeed = MultiByteToWideChar(CP_ACP, 0, sSrc.c_str(), -1, NULL, 0);
if(0 == iNeed)
{
WriteToLog("util::CodeToUtf8: MultiByteToWideChar == 0, ErrorCode=%d, sSrc=%s", GetLastError(), sSrc.c_str());
return false;
}
std::wstring sWstr(iNeed, 0);
MultiByteToWideChar(CP_ACP, 0, sSrc.c_str(), -1, &sWstr[0], sWstr.size());
iNeed = WideCharToMultiByte(CP_UTF8, 0, sWstr.c_str(), -1, NULL, 0, NULL, NULL);
if(0 == iNeed)
{
WriteToLog("util::CodeToUtf8: WideCharToMultiByte == 0, ErrorCode=%d", GetLastError());
return false;
}
sDst.resize(iNeed, 0);
WideCharToMultiByte(CP_UTF8, 0, sWstr.c_str(), -1, &sDst[0], sDst.size(), NULL, NULL);
return true;
}
bool CodeToUtf8(const std::string &sSrc, std::string &sDst) { int iNeed = MultiByteToWideChar(CP_ACP, 0, sSrc.c_str(), -1, NULL, 0); if(0 == iNeed) { WriteToLog("util::CodeToUtf8: MultiByteToWideChar == 0, ErrorCode=%d, sSrc=%s", GetLastError(), sSrc.c_str()); return false; } std::wstring sWstr(iNeed, 0); MultiByteToWideChar(CP_ACP, 0, sSrc.c_str(), -1, &sWstr[0], sWstr.size()); iNeed = WideCharToMultiByte(CP_UTF8, 0, sWstr.c_str(), -1, NULL, 0, NULL, NULL); if(0 == iNeed) { WriteToLog("util::CodeToUtf8: WideCharToMultiByte == 0, ErrorCode=%d", GetLastError()); return false; } sDst.resize(iNeed, 0); WideCharToMultiByte(CP_UTF8, 0, sWstr.c_str(), -1, &sDst[0], sDst.size(), NULL, NULL); return true; }
解码,Utf-8转当前默认编码
bool DecodeFromUtf8(const std::string &sSrc, std::string &sDst) { int iNeed = MultiByteToWideChar(CP_UTF8, 0, sSrc.c_str(), -1, NULL, 0); if(0 == iNeed) { WriteToLog("util::DecodeFromUtf8: MultiByteToWideChar == 0, ErrorCode=%d, sSrc=%s", GetLastError(), sSrc.c_str()); return false; } std::wstring sWstr(iNeed, 0); MultiByteToWideChar(CP_UTF8, 0, sSrc.c_str(), -1, &sWstr[0], sWstr.size()); iNeed = WideCharToMultiByte(CP_ACP, 0, sWstr.c_str(), -1, NULL, 0, NULL, NULL); if(0 == iNeed) { WriteToLog("util::DecodeFromUtf8: WideCharToMultiByte == 0, ErrorCode=%d", GetLastError()); return false; } sDst.resize(iNeed, 0); WideCharToMultiByte(CP_ACP, 0, sWstr.c_str(), -1, &sDst[0], sDst.size(), NULL, NULL); return true; }
标签:
原文地址:http://www.cnblogs.com/chaikefusibushiji/p/4334586.html