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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM