在进行windows编程时,常常遇到不同字符编码之间的转换以对应不同的输出格式,c/c++开发分享宽字节UTF-8、多字节互转介绍宽字节utf-8编码格式和多字节之间的项目转换。分别调用windows底层函数multibytetowidechar和 widechartomultibyte实现。
1.utf-8转多字节
std::string u82mb(const char* cont) { if (null == cont) { return ""; } int num = multibytetowidechar(cp_utf8, null, cont, -1, null, null); if (num <= 0) { return ""; } wchar_t* buffw = new (std::nothrow) wchar_t[num]; if (null == buffw) { return ""; } multibytetowidechar(cp_utf8, null, cont, -1, buffw, num); int len = widechartomultibyte(cp_acp, 0, buffw, num - 1, null, null, null, null); if (len <= 0) { delete[] buffw; return ""; } char* lpsz = new (std::nothrow) char[len + 1]; if (null == lpsz) { delete[] buffw; return ""; } widechartomultibyte(cp_acp, 0, buffw, num - 1, lpsz, len, null, null); lpsz[len]=' '; delete[] buffw; std::string rtn(lpsz); delete[] lpsz; return rtn; }
2.多字节转utf-8
std::string mb2u8(const char* cont) { if (null == cont) { return ""; } int num = multibytetowidechar(cp_acp, null, cont, -1, null, null); if (num <= 0) { return ""; } wchar_t* buffw = new (std::nothrow) wchar_t[num]; if (null == buffw) { return ""; } multibytetowidechar(cp_acp, null, cont, -1, buffw, num); int len = widechartomultibyte(cp_utf8, 0, buffw, num - 1, null, null, null, null); if (len <= 0) { delete[] buffw; return ""; } char* lpsz = new (std::nothrow) char[len + 1]; if (null == lpsz) { delete[] buffw; return ""; } widechartomultibyte(cp_utf8, 0, buffw, num - 1, lpsz, len, null, null); lpsz[len]=' '; delete[] buffw; std::string rtn(lpsz); delete[] lpsz; return rtn ; }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/608299.html