utf-8 字符串转 unicode 字符串

utf-8编码简介

utf-8编码是一种变长编码, 中文字符用三个byte来存储,而编码范围在 0 到 0x7f 则使用1个字节存储

Number of bytesBits for code pointFirst code pointLast code pointByte1Byte2Byte3Byte4
17U+0000U+007F0xxxxxxx
211U+0080U+07FF110xxxxx10xxxxxx
316U+0800U+FFFF1110xxxx10xxxxxx10xxxxxx
421U+10000U+10FFFF11110xxx10xxxxxx10xxxxxx10xxxxxx

以下是编码例子,这些都是来自于维基百科

这里写图片描述

以下代码能把 utf-8 多字节字符串,转换成为unicode 字符串,如转载请注明出处

static int z_pos(uint8_t x)
{
    for (int i = 0; i < 5; i++, x <<= 1) {
        if ( (x & 0x80) == 0 )
            return i;
    }

    return 4;
}

// convert UTF-8 string to wstring
std::wstring utf8_to_wstring(const std::string& str)
{
    std::wstring loc;
    uint8_t mask[5] = { 0x7f, 0x3f, 0x1f, 0x0f, 0x7};

    for (size_t i = 0; i < str.length();) {
        int byte_cnt = z_pos(str[i]);
        uint16_t sum = str[i] & mask[byte_cnt];

        for (size_t j = 1; j < byte_cnt; j++) {
            sum <<= 6;
            sum |= str[i+j] & mask[1];
        }

        i += byte_cnt ? byte_cnt : 1;
        loc.push_back(sum);
    }

    return loc;
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值