如何打印unicode字符的位表示

How to print bit representation of unicode character

我尝试像图像一样获取 unicode 字符的二进制 utf-8 表示:

但这只适用于 <128 个字符:

这是我的代码:

#include <string>
#include <iostream>
#include <windows.h>

std::string contoutf8(std::wstring str)
{    
    int utf8_size = WideCharToMultiByte(CP_UTF8, 0, str.c_str(),
                    str.length(), nullptr, 0, nullptr, nullptr);
    std::string utf8_str(utf8_size, '[=10=]');
    WideCharToMultiByte(CP_UTF8, 0, str.c_str(), str.length(), 
                    &utf8_str[0], utf8_size, nullptr, nullptr);
    return utf8_str;
}

std::string contobin(std::string str)
{
    std::string result;
    for(int i=0; i<str.size(); ++i)
        for(int j=0; j < 8; ++j)
            result.append((1<<j) & str[i] ? "1" : "0");
    return result;
}

int main()
{
    std::wstring str  = L"\u20AC";
    std::string utf8 = contoutf8(str);
    std::string bin  = contobin(utf8);

    std::cout << bin;
}

我检查了很多代码组合(上面是最后一个代码)但没有一个以格式 11 给出二进制表示...这表明这是 unicode 字符。

两个问题:

  1. 反转位模式(二进制从左到右读取位 7 到 0)。

  2. 符号扩展

std::string contobin(std::string str)
{
    std::string result;
    for(int i=0; i<str.size(); ++i)
        for(int j=8; j--;) {
            result.append((1<<j) & uint8_t(str[i]) ? "1" : "0");
        }
    return result;
}

与其自己转换为二进制,不如考虑使用 std::bitset,如下所示:

#include <bitset>

std::string contoutf8(std::wstring str)
{    
    int utf8_size = WideCharToMultiByte(CP_UTF8, 0, str.c_str(),
                    str.length(), nullptr, 0, nullptr, nullptr);
    std::string utf8_str(utf8_size, '[=10=]');
    WideCharToMultiByte(CP_UTF8, 0, str.c_str(), str.length(), 
                    &utf8_str[0], utf8_size, nullptr, nullptr);
    return utf8_str;
}

int main()
{
    std::wstring str  = L"\u20AC";
    std::string utf8 = contoutf8(str);

    std::copy(utf8.begin(), utf8.end(), std::ostream_iterator<std::bitset<8>>(std::cout, "\t"));
}