Windows下简单的编码转换
/********************************************************************************** * Function : WCharToChar * Description : wide char to muliple char ***********************************************************************************/ int WCharToChar(UINT PageCode, std::wstring strWChar, std::string &strChar) { int nSize = WideCharToMultiByte(PageCode, 0, strWChar.c_str(), -1, NULL, 0, NULL, NULL); if( nSize <= 0 ) return -1; strChar.clear(); int ret = 0; char *pszDest = new char[nSize+1]; if( pszDest ) { memset( pszDest, 0, nSize+1 ); ret = WideCharToMultiByte(PageCode, 0, strWChar.c_str(), -1, pszDest, nSize, NULL, FALSE); pszDest[nSize] = '\0'; strChar = pszDest; } SAFE_DELETE_ARRAY( pszDest ); return ret; } int WCharToChar(std::wstring strWChar, std::string &strChar) { return WCharToChar( GetOEMCP(), strWChar, strChar ); } /********************************************************************************** * Function : CharToWChar * Description : muliple char to wide char ***********************************************************************************/ int CharToWChar(UINT PageCode, std::string strChar, std::wstring &strWChar) { int nSize = MultiByteToWideChar(CP_ACP, 0, strChar.c_str(), -1, 0, 0); if( nSize <= 0 ) return -1; strWChar.clear(); int ret = 0; wchar_t *pszDest = new wchar_t[nSize+1]; if( pszDest ) { memset( pszDest, 0, nSize ); ret = MultiByteToWideChar(PageCode, 0, strChar.c_str(), -1, pszDest, nSize); pszDest[nSize] = L'\0'; strWChar = pszDest; } SAFE_DELETE_ARRAY( pszDest ); return ret; } int CharToWChar(std::string strChar, std::wstring &strWChar) { return CharToWChar( GetOEMCP(), strChar, strWChar ); } /********************************************************************************** * Function : GB2312ToUtf8 * Description : GB2312 to UTF-8 ***********************************************************************************/ int GB2312ToUtf8A( const char *pszGB2312, std::string &strUtf8 ) { int ret = 0; std::wstring wGB2312; CharToWChar( CP_ACP, pszGB2312, wGB2312 ); ret = WCharToChar( CP_UTF8, wGB2312, strUtf8 ); return ret; } int GB2312ToUtf8W( const wchar_t *pszGB2312, std::string &strUtf8 ) { int ret = 0; ret = WCharToChar( CP_UTF8, pszGB2312, strUtf8 ); return ret; } /********************************************************************************** * Function : Utf8ToGB2312 * Description : UTF-8 to GB2312 ***********************************************************************************/ int Utf8ToGB2312A( const char *pszUtf8, std::string &strGB2312 ) { int ret = 0; std::wstring wUnicode; CharToWChar( CP_UTF8, pszUtf8, wUnicode ); ret = WCharToChar( CP_ACP, wUnicode, strGB2312 ); return ret; } int Utf8ToGB2312W( const char *pszUtf8, std::wstring &strGB2312 ) { int ret = 0; ret = CharToWChar( CP_UTF8, pszUtf8, strGB2312 ); return ret; } |