UTF-8和Unicode互转
1、Unicode转UTF-8
1 void CodeCovertTool::UNICODE_to_UTF8(const CString& unicodeString, std::string& str) 2 {//Unicode转UTF8 3 int stringLength = ::WideCharToMultiByte(CP_UTF8, NULL, unicodeString, wcslen(unicodeString), NULL, 0, NULL, NULL); 4 5 char* buffer = new char[stringLength + 1]; 6 ::WideCharToMultiByte(CP_UTF8, NULL, unicodeString, wcslen(unicodeString), buffer, stringLength, NULL, NULL); 7 buffer[stringLength] = '\0'; 8 9 str = buffer; 10 11 delete[] buffer; 12 }
1 std::string CodeCovertTool::UnicodeToUtf8(const wchar_t* buf) 2 {//Unicode转UTF8 3 int len = ::WideCharToMultiByte(CP_UTF8, 0, buf, -1, NULL, 0, NULL, NULL); 4 if (len == 0) return ""; 5 6 std::vector<char> utf8(len); 7 ::WideCharToMultiByte(CP_UTF8, 0, buf, -1, &utf8[0], len, NULL, NULL); 8 9 return &utf8[0]; 10 }
2、UTF-8转Unicode
1 std::wstring CodeCovertTool::Utf8ToUnicode(const char* buf) 2 {//UTF8转Unicode 3 int len = ::MultiByteToWideChar(CP_UTF8, 0, buf, -1, NULL, 0); 4 if (len == 0) return _T(""); 5 6 std::vector<wchar_t> unicode(len); 7 ::MultiByteToWideChar(CP_UTF8, 0, buf, -1, &unicode[0], len); 8 9 return &unicode[0]; 10 }
1 CString CodeCovertTool::Utf8ToUnicode(const std::string &utf8_str) 2 {//UTF8转Unicode 3 int len; 4 len = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)utf8_str.c_str(), -1, NULL,0); 5 WCHAR * wszUnicode = new WCHAR[len+1]; 6 memset(wszUnicode, 0, len * 2 + 2); 7 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)utf8_str.c_str(), -1, wszUnicode, len); 8 CString ss=wszUnicode; 9 delete wszUnicode; 10 return ss; 11 }
3、Ansi转Unicode
1 std::wstring CodeCovertTool::AnsiToUnicode(const char* buf) 2 {//Ansi转Unicode 3 int len = ::MultiByteToWideChar(CP_ACP, 0, buf, -1, NULL, 0); 4 if (len == 0) return L""; 5 6 std::vector<wchar_t> unicode(len); 7 ::MultiByteToWideChar(CP_ACP, 0, buf, -1, &unicode[0], len); 8 9 return &unicode[0]; 10 }
4、Unicode转Ansi
1 std::string CodeCovertTool::UnicodeToAnsi(const wchar_t* buf) 2 {//Unicode转Ansi 3 int len = ::WideCharToMultiByte(CP_ACP, 0, buf, -1, NULL, 0, NULL, NULL); 4 if (len == 0) return ""; 5 6 std::vector<char> utf8(len); 7 ::WideCharToMultiByte(CP_ACP, 0, buf, -1, &utf8[0], len, NULL, NULL); 8 9 return &utf8[0]; 10 }