UTF8转Unicode

本文介绍了一种将UTF8编码转换为Unicode编码的算法实现,包括一个关键函数GetUtf8ByteNumForWord来确定每个字符的UTF8字节数,并通过示例代码展示了整个转换过程。此外还提供了一个测试实例,读取文件并显示转换后的Unicode字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

int GetUtf8ByteNumForWord(char firstCh)
{
    int nRet=0;
    __asm
    {    
        movzx ecx,byte ptr[firstCh]
        and ecx,0xE0
        jz  done
        test ecx,0x80
        jnz lbm
        mov nRet,1
        jmp done
lbm:
        cmp cl,0xE0
        jz  lb3
        cmp cl,0x0C
        jz  lb2
        jmp done
lb3:
        mov nRet,3
        jmp done
lb2:
        mov nRet,2
done:
    }
    return nRet;
}

void Utf8ToUnicode(const char* utf8, int len, wchar_t *unicode)
{
    int i = 0;
    int j = 0;
    char* temp=(char*)unicode;
    //循环解析
    while (i < len)
    {   
        int nByteNum=GetUtf8ByteNumForWord(utf8[i]);
        if (nByteNum==0)
        {
            return;
        }
        switch(nByteNum)
        {
        case 1:
            temp[j] = utf8[i];
            temp[j+1]=0;
            break;
        case 2:
            temp[j] = utf8[i];
            temp[j + 1] = utf8[i + 1];
            break;
        case 3:
            //这里就开始进行UTF8->Unicode
            temp[j + 1] = ((utf8[i] & 0x0F) << 4) | ((utf8[i + 1] >> 2) & 0x0F);
            temp[j] = ((utf8[i + 1] & 0x03) << 6) + (utf8[i + 2] & 0x3F);
            break;
        default:
            break;    
        }
        j+=2;
        i+=nByteNum;
    }
    temp[j]=0;
    temp[j+1]=0;
}

测试代码如下:

 

std::ifstream fin("debug\\Test.txt");
const unsigned int L_MAX_LINE=1024;
char utf8[L_MAX_LINE];
wchar_t unicode[L_MAX_LINE];
while(fin.getline(utf8,L_MAX_LINE))
{
    Utf8ToUnicode(utf8,strlen(utf8),unicode);
    MessageBoxW(0,unicode,0,0);
}
fin.close();

 

参考:

https://www.yuque.com/docs/share/d25a5d6a-2056-4d52-8941-b7a4cec74d5d

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值