Win32字符串编码格式转化
2016-07-29 16:03
260 查看
1.ascii转unicode
2.utf8转unicode
3.unicode 转ascii
4.unicode转utf8
5.ascii转utf8
6.utf8转ascii
总结:转编码格式转化的时候,如果转化的双方不是unicode编码,那么一定要通过unicode做中转,也就是说一定要先转化成unicode,然后再转化成目标编码。
转化时怎样决定编码(使用CP_UTF8还是CP_ACP),只要是转unicode,那么如果是utf8转unicode(或者unicode转utf8),那么肯定用CP_UTF8;
如果是ascii转unicode(或者unicode转ascii),那么肯定用CP_ACP。
wstring asciiToUnicode(string asciiStr) { int widesize = MultiByteToWideChar(CP_ACP, 0, (char*)asciiStr.c_str(), -1, NULL, 0); if(0 == widesize) { return std::wstring(); } std::vector<wchar_t> resultstring(widesize); int count = MultiByteToWideChar(CP_ACP, 0, (char*)asciiStr.c_str(), -1, &resultstring[0], widesize); if(0 == count) { return std::wstring(); } return std::wstring(&resultstring[0]); }
2.utf8转unicode
std::wstring utf8ToUnicode(const std::string &s) { if (s.length() == 0) { return wstring(); } // compute the length of the buffer we'll need int charcount = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, NULL, 0); if (charcount == 0) { return wstring(); } // convert wchar_t* buf = new wchar_t[charcount]; MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, buf, charcount); wstring result(buf); delete[] buf; return result; }
3.unicode 转ascii
string unicodeToAscii(wstring unicodeStr) { // compute the length of the buffer we'll need int charcount = WideCharToMultiByte(CP_ACP, 0, unicodeStr.c_str(), -1, NULL, 0, NULL, NULL); if (charcount == 0) { return string(); } // convert char *buf = new char[charcount]; WideCharToMultiByte(CP_ACP, 0, unicodeStr.c_str(), -1, buf, charcount, NULL, NULL); string result(buf); delete[] buf; return result; }
4.unicode转utf8
string unicodeToUtf8(wstring unicodeStr) { int utf8size = ::WideCharToMultiByte(CP_UTF8, 0, unicodeStr.c_str(), -1, NULL, 0, NULL, NULL); if(0 == utf8size) { return std::string(); } std::vector<char> resultstr(utf8size); int count = ::WideCharToMultiByte(CP_UTF8, 0, unicodeStr.c_str(), -1, &resultstr[0], utf8size, NULL, NULL); if(0 == count) { return std::string(); } return std::string(&resultstr[0]); }
5.ascii转utf8
string PublicFunction::asicToUtf8(string asic) { return unicodeToUtf8(asciiToUnicode(asic)); }
6.utf8转ascii
string utf8ToAsic(string utf8) { return unicodeToAscii(utf8ToUnicode(utf8)); }
总结:转编码格式转化的时候,如果转化的双方不是unicode编码,那么一定要通过unicode做中转,也就是说一定要先转化成unicode,然后再转化成目标编码。
转化时怎样决定编码(使用CP_UTF8还是CP_ACP),只要是转unicode,那么如果是utf8转unicode(或者unicode转utf8),那么肯定用CP_UTF8;
如果是ascii转unicode(或者unicode转ascii),那么肯定用CP_ACP。
相关文章推荐
- ASP编码必备的8条原则
- XML指南——XML编码
- C#中字符串编码处理
- ExtJS中文乱码之GBK格式编码解决方案及代码
- 程序员趣味读物 谈谈Unicode编码
- 文本文件编码方式区别
- C语言安全编码之数值中的sizeof操作符
- C#实现获取文本文件的编码的一个类(区分GB2312和UTF8)
- VC中BASE64编码和解码使用详解
- 计算机中的字符串编码、乱码、BOM等问题详解
- Base64编码解码原理及C#编程实例
- C#编码好习惯小结
- javascript编码的几个方法详细介绍
- UTF8编码开发中页面空白问题的解决方法
- php生成固定长度纯数字编码的方法
- 重新restore了mysql到另一台机器上后mysql 编码问题报错
- c# Base64编码和图片的互相转换代码
- java自动根据文件内容的编码来读取避免乱码
- PHP写入WRITE编码为UTF8的文件的实现代码
- 设置php页面编码的两种方法示例介绍