gpt4 book ai didi

c++ - Unicode char 到 wstring

转载 作者:行者123 更新时间:2023-11-30 05:41:15 30 4
gpt4 key购买 nike

我正在尝试将 C# 字符串发送到 C++ wstring 数据,反之亦然。 (通过 TCP)。

我成功地从 C#(如 Unicode、UTF-16)发送字符串数据,并通过 char 数组将其导入 C++。

但我不知道如何将 char 数组转换为 wstring。

这是 c++ 使用 utf-16 获取“abcd”时的样子

    [0] 97 'a'  char
[1] 0 '\0' char
[2] 98 'b' char
[3] 0 '\0' char
[4] 99 'c' char
[5] 0 '\0' char
[6] 100 'd' char
[7] 0 '\0' char

这是当 c++ 使用 utf-16 获得“한글”时的样子

    [0] 92 '\\' char
[1] -43 '?' char
[2] 0 '\0' char
[3] -82 '?' char

这就是当 c++ 使用 utf-16 获得“日本语”时的样子

    [0] -27 '?' char
[1] 101 'e' char
[2] 44 ',' char
[3] 103 'g' char
[4] -98 '?' char
[5] -118 '?'char

由于 UTF-8 不支持所有日文字符,我尝试通过 UTF-16(基本上使用 C# 字符串)获取数据。但是我无法使用我找到的所有方法将这些 char 数组转换为 wstring。

这是我之前尝试过的

std::wstring_convert<std::codecvt_utf16<wchar_t>> myconv 
-> what wchar have to have
[0] 54620 '한' wchar_t
[1] 44544 '글' wchar_t
->What it have after using this
[0] 23765 '峕' wchar_t
[1] 174 '®' wchar_t

/

std::wstring wsTmp(s.begin(), s.end()); 

-> what wchar have to have
[0] 54620 '한' wchar_t
[1] 44544 '글' wchar_t

->What it have after using this
[0] 92 '\\' wchar_t
[1] 65493 'ᅰ' wchar_t
[2] 0 '\0' wchar_t
[3] 65454 'ᆴ' wchar_t

在它们中,我将 char 数组更改为字符串并将其更改为 wstring那失败了……

有谁知道如何将非英语 UTF-16 char 数据转换为 wstring 数据?

添加:C# 端代码

byte[] sendBuffer = Encoding.Unicode.GetBytes(Console.ReadLine());
clientSocket.Send(sendBuffer);

并将'한글'转换成类似字节的形式

    [0] 92  byte
[1] 213 byte
[2] 0 byte
[3] 174 byte

最佳答案

I try to send C# string data to C++ wstring data and vice vera. (by TCP)

I succesed to send string data from C#(as Unicode, UTF-16) and get it at C++ by char array.

使用 UTF-8 而不是 UTF-16 传输数据会更好,也更便携。

But I have no idea how to convert char array to wstring.

wchar_t 为 16 位的平台上,例如 Windows(我假设您使用的是 Windows,因为您使用的是 C#),您可以将 char 数组内容复制为- 直接进入std::wstring,例如:

char *buffer = ...;
int buflen = ...;

std::wstring wstr(reinterpret_cast<wchar_t*>(buffer), buflen / sizeof(wchar_t));

如果您需要支持 wchar_t 为 32 位的平台,您可以使用 std::wstring_convert:

char *buffer = ...;
int buflen = ...;

std::wstring_convert<std::codecvt_utf16<wchar_t>, wchar_t> conv;
std::wstring wstr = conv.from_bytes(std::string(buffer, buflen));
// or:
// std::wstring wstr = conv.from_bytes(buffer, buffer+buflen);

由于 wchar_t 不是很便携,请考虑使用 std::u16string/char16_t 代替(如果您使用的编译器支持 C++11 或更高版本),因为它们是专门为 UTF-16 数据设计的。

Since UTF-8 dosen't support all japanese character

是的,确实如此。 Unicode 是实际的字符集,UTF 只是将 Unicode 代码点表示为字节序列的编码。 ALL UTF(UTF-7、UTF-8、UTF-16 和 UTF-32)支持ENTIRE Unicode 字符集,UTF 旨在允许丢失-从一个 UTF 到另一个 UTF 的转换更少。

关于c++ - Unicode char 到 wstring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31216566/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com