MFC/C++用Char*(Byte*)读取文件utf-8的文件乱码—-解码

//utf8Str:以字节(char*或者Byte*)读取中文的字符串(乱码)
CString UTF8toUnicode(const char* utf8Str)
{
    UINT theLength=strlen(utf8Str);
    return UTF8toUnicode(utf8Str,theLength);
}

CString UTF8toUnicode(const char* utf8Str,UINT length)
{
    CString unicodeStr;
    unicodeStr=_T("");

    if (!utf8Str)
        return unicodeStr;

    if (length==0)
        return unicodeStr;


    WCHAR chr=0;//一个中文字符
    for (UINT i=0;i<length;)
    {
        //UTF8的三种中文格式
        if ((0x80&utf8Str[i])==0) //只占用一个字节
        {
            chr=utf8Str[i];
            i++;
        }
        else if((0xE0&utf8Str[i])==0xC0) //占用两个字节
        {
            chr =(utf8Str[i+0]&0x3F)<<6;
            chr|=(utf8Str[i+1]&0x3F);
            i+=2;
        }
        else if((0xF0&utf8Str[i])==0xE0)//占用三个字节
        {
            chr =(utf8Str[i+0]&0x1F)<<12;
            chr|=(utf8Str[i+1]&0x3F)<<6;
            chr|=(utf8Str[i+2]&0x3F);
            i+=3;
        }

        else 
        {
            return unicodeStr;
        }
        unicodeStr.AppendChar(chr);
    }

    return unicodeStr;
}

UTF-8百度百科仔细研究!!!

转自:https://blog.csdn.net/chenlu5201314/article/details/8912707?utm_medium=distribute.pc_relevant.none-task-blog-baidujs-3

原文链接: https://www.cnblogs.com/xmr183729/p/13307346.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    MFC/C++用Char*(Byte*)读取文件utf-8的文件乱码----解码

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/366368

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 下午4:40
下一篇 2023年3月2日 下午4:40

相关推荐