1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > C++ 字符串/内存数据编码转换(ANSI UNICODE UTF8)

C++ 字符串/内存数据编码转换(ANSI UNICODE UTF8)

时间:2021-09-28 04:18:01

相关推荐

C++ 字符串/内存数据编码转换(ANSI UNICODE UTF8)

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;}

上面这两个函数对于带结束符的字符串也是通用的。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。