我使用wstring_convert & codecvt_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_utf16 中的默认参数是大端。
但是,测试程序显示的字节如下
60 4人7天59 20 00 68 00 65 00 00 6c 00 6 c 00 6 f 00 20 00 63 00 68 00 6 e 00 65 00 00 00 74 00 00 00 73 00 00 00 2 d e 87 65 4b 6d d5 8b 8b
在小安迪安。
我分别在Visual 2013和clang上运行了测试代码,并得到了相同的结果。
那么,为什么codecvt_utf8_utf16的大端模式对这些转换没有任何影响呢?
发布于 2016-08-28 10:59:03
您引用的相同页面表示,little_endian标志仅用于输入。输出是代码点序列,而不是字节流。每个代码点都使用平台的任何正常代码来表示--在您的例子中,是小endian。
您的程序只是告诉您如何在内存中表示char16_t。
https://stackoverflow.com/questions/39190336
复制相似问题