utf-8 utf-16对比windows系统下wchar_t和char中文字符的二进制对比

对比的源程序(cpp) :


// 针对汉字的utf-8 和utf-16对比

#include "stdafx.h"
#include "windows.h"
#include <cstdint>
#include <iostream>
#include <bitset>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    char *pc = "中国";
    cout << pc[0] << pc[1] << endl;// 中
    wchar_t* lpString = L"hi中国";
    wcout.imbue(locale("chs"));
    wcout << lpString[3] << endl; // 国
    cout << "------------wchar_t to utf-8----------------" << endl;
    char uf8[10] = { 0 };
    int nLenOfUf8, nReturnlen;
    nLenOfUf8 = WideCharToMultiByte(CP_UTF8, 0, lpString, -1, NULL, 0, NULL, NULL);
    //Header: Declared in Winnls.h; include Windows.h.  
    if (!nLenOfUf8)
        return false;
    nReturnlen = WideCharToMultiByte(CP_UTF8, 0, lpString, -1, uf8, nLenOfUf8, NULL, NULL);
    if (!nReturnlen)
    {
        return false;
    }
    setlocale(LC_ALL, "");
    cout << uf8[0] << uf8[1] << endl; // hi
    cout << uf8 << " :" << strlen(uf8) << endl; // hi乱码   8

    bitset<16> b(lpString[2]);
    cout << "wchar_t:  " << b << endl;// wchar_t (对后面的utf8就知道wchar_t就是utf-16)
    bitset<8> b1(uf8[2]);//1110 XXXX // 高4位
    bitset<8> b2(uf8[3]);//10XX XXXX // 中间6位
    bitset<8> b3(uf8[4]);//10XX XXXX // 低6位
    cout << "utf8: " << b1 << ' ' << b2 << ' ' << b3 << endl;
    cout << "---------wchar_t is utf16----utf8 to utf16-------------------" << endl;
    wchar_t ch[10] = { 0 };
    bitset<16> b4(((uf8[2] & 0x0f) << 12)//根据规则计算,把'中' '国'由utf8转成utf16
        + ((uf8[3] & 0x3f) << 6) + (uf8[4] & 0x3f) );
    cout << "utf-16: " << b4 << endl; // 中
    ch[0] = ((uf8[2] & 0x0f) << 12) + ((uf8[3] & 0x3f) << 6) + (uf8[4] & 0x3f)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值