【发布时间】:2015-07-04 16:20:55
【问题描述】:
我最近发现了 <codecvt> 标头,所以我想在 UTF-8 和 UTF-16 之间进行转换。
我在 C++11 中使用 codecvt_utf8_utf16 和 wstring_convert 方面。
我遇到的问题是,当我尝试将 UTF-16 字符串转换为 UTF-8,然后再次转换为 UTF-16 时,字节序会发生变化。
对于此代码:
#include <codecvt>
#include <string>
#include <locale>
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
wstring_convert<codecvt_utf8_utf16<char16_t>, char16_t>
convert;
u16string utf16 = u"\ub098\ub294\ud0dc\uc624";
cout << hex << "UTF-16\n\n";
for (char16_t c : utf16)
cout << "[" << c << "] ";
string utf8 = convert.to_bytes(utf16);
cout << "\n\nUTF-16 to UTF-8\n\n";
for (unsigned char c : utf8)
cout << "[" << int(c) << "] ";
cout << "\n\nConverting back to UTF-16\n\n";
utf16 = convert.from_bytes(utf8);
for (char16_t c : utf16)
cout << "[" << c << "] ";
cout << endl;
}
我得到这个输出:
UTF-16
[b098] [b294] [d0dc] [c624]
UTF-16 到 UTF-8
[eb] [82] [98] [eb] [8a] [94] [ed] [83] [9c] [ec] [98] [a4]
转换回 UTF-16
[98b0] [94b2] [dcd0] [24c6]
当我将wstring_convert 的第三个模板参数更改为std::little_endian 时,字节会反转。
我错过了什么?
【问题讨论】:
-
感谢您的回复,这很奇怪,我使用的是 gcc 5,今晚我将尝试从源代码编译它,看看我是否得到相同的行为。
-
将编译器切换到 gcc 也不会在 coliru 上重现这一点:coliru.stacked-crooked.com/a/cbac3e56d8f55c30
-
嗯,它可以在 OS X 和 Windows 上运行,所以我猜 libstdc++ 有问题,我将它作为一个错误报告。
标签: c++11 encoding endianness codecvt