簡體   English   中英

std :: codecvt_utf8_utf16不會在big-endian中將utf-8轉換為utf-16

[英]std::codecvt_utf8_utf16 doesn't convert utf-8 to utf-16 in big-endian

我使用wstring_convertcodecvt_utf8_utf16 utf-8編碼的字符串轉換為utf-16的字符串

這是我測試的示例代碼:

#include <iostream>
#include <codecvt>
#include <string>

#include <fstream>
#include <cstdint>

std::u16string UTF8ToWide(const std::string& utf_str)
{
    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> converter;
    return converter.from_bytes(utf_str);
}

void DisplayBytes(const void* data, size_t len)
{
    const uint8_t* src = static_cast<const uint8_t*>(data);
    for (size_t i = 0; i < len; ++i) {
        printf("%.2x ", src[i]);
    }
}

// the content is:"你好 hello chinese test 中文測試"
std::string utf8_s = "\xe4\xbd\xa0\xe5\xa5\xbd hello chinese test \xe4\xb8\xad\xe6\x96\x87\xe6\xb5\x8b\xe8\xaf\x95";

int main()
{
    auto ss = UTF8ToWide(utf8_s);
    DisplayBytes(ss.data(), ss.size() * sizeof(decltype(ss)::value_type));
    return 0;
}

根據參考手冊構面codecvt_utf8_utf16std::codecvt_mode的默認參數為big-endian

但是,測試程序將字節顯示如下

60 4f 7d 59 20 00 68 00 65 00 6c 00 6c 00 6f 00 20 00 63 00 68 00 69 00 6e 00 65 00 73 00 65 00 20 00 74 00 65 00 73 00 74 00 20 00 2d 4e 87 65 4b 6d d5 8b

在little-endian中。

我分別在Visual Studio 2013和clang上運行了測試代碼,最終得到了相同的結果。

那么,為什么codecvt_utf8_utf16的big-endian模式對這些轉換沒有任何影響?

您引用的同一頁面上說little_endian標志僅用於輸入。 輸出是代碼點序列,而不是字節流。 每個代碼點都使用平台正常的任何形式表示-在您的情況下為little endian。

您的程序只是告訴您如何在內存中表示char16_t

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM