1、对于字符串来说,并且最后带有结束符:'\0'的字符串,使用下面的两个函数即可:
std::string ANSItoUTF8(const char * ansi){int len = MultiByteToWideChar(CP_ACP, 0, ansi, -1, NULL, 0);wchar_t* wstr = new wchar_t[len+1];memset(wstr, 0, len+1);MultiByteToWideChar(CP_ACP, 0, ansi, -1, wstr, len);len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);char* str = new char[len+1];memset(str, 0, len+1);WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);if(wstr) delete[] wstr;std::string ret = str;if(str) delete[] str;return ret;}
std::string UTF8toANSI(const char* utf8){int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);wchar_t* wstr = new wchar_t[len+1];memset(wstr, 0, len+1);MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);char* str = new char[len+1];memset(str, 0, len+1);WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);if(wstr) delete[] wstr;std::string ret = str;if(str) delete[] str;return ret;}
ANSI和UNICODE的转换以及UNICODE与UTF8之间的转换,就是上面两个函数的简化版本,我们应该可以自行写出。
2、对于内存中的数据来说,比如我们将一张图片读入到内存,因为在数据的中间某个位置可能存在结束符:'\0',所以上面两个函数就失效了,但是我们可以对上面两个函数稍加变换即可:
std::string ANSItoUTF8(const char * ansi, int iSize, int& oSize){int lenUNICODE = MultiByteToWideChar(CP_ACP, 0, ansi, iSize, NULL, 0);wchar_t* wstr = new wchar_t[lenUNICODE + 1];memset(wstr, 0, lenUNICODE + 1);lenUNICODE = MultiByteToWideChar(CP_ACP, 0, ansi, iSize, wstr, lenUNICODE);int lenUTF8 = WideCharToMultiByte(CP_UTF8, 0, wstr, lenUNICODE, NULL, 0, NULL, NULL);char* str = new char[lenUTF8 + 1];memset(str, 0, lenUTF8 + 1);lenUTF8 = WideCharToMultiByte(CP_UTF8, 0, wstr, lenUNICODE, str, lenUTF8, NULL, NULL);oSize = lenUTF8;std::string ret(str, lenUTF8);if (wstr) delete[] wstr;if (str) delete[] str;return ret;}
std::string UTF8toANSI(const char* utf8, int iSize, int& oSize){int lenUNICODE = MultiByteToWideChar(CP_UTF8, 0, utf8, iSize, NULL, 0);wchar_t* wstr = new wchar_t[lenUNICODE + 1];memset(wstr, 0, lenUNICODE + 1);lenUNICODE = MultiByteToWideChar(CP_UTF8, 0, utf8, iSize, wstr, lenUNICODE);int lenANSI = WideCharToMultiByte(CP_ACP, 0, wstr, lenUNICODE, NULL, 0, NULL, NULL);char* str = new char[lenANSI + 1];memset(str, 0, lenANSI + 1);lenANSI = WideCharToMultiByte(CP_ACP, 0, wstr, lenUNICODE, str, lenANSI, NULL, NULL);oSize = lenANSI;std::string ret(str, lenANSI);if (wstr) delete[] wstr;if (str) delete[] str;return ret;}
上面这两个函数对于带结束符的字符串也是通用的。