【问题标题】:C# .Net framework strings encoding from utf-8 bytes从 utf-8 字节编码的 C# .Net 框架字符串
【发布时间】:2016-01-05 21:02:40
【问题描述】:

我用 C# 编写了应用程序,该应用程序使用套接字(udp libenet)通过网络从服务器接收数据。

在我的应用程序中,我具有处理数据包中发送的原始字节的功能。 功能之一是读取字符串,由 \0 分隔。

我的问题是我通过服务器将 UTF-8 编码的字符串发送到 C# 应用程序,但是当我使用这些字符串在控件中显示它们时,我得到的是乱码而不是波兰字母。

从缓冲区读取字符串的函数:

public override string ReadString()
{
            
    StringBuilder sb = new StringBuilder();

    while (true)
    {
        byte b;
        if (Remaining > 0)
            b = ReadByte();
        else
            b = 0;

        if (b == 0) break;

        // Probably here is the problem. Checked other encodings etc., but still same 
        sb.Append(Encoding.UTF8.GetString(new byte[] { b }, 0, 1));
    }

    return sb.ToString();
}

函数覆盖,来自:

public class BitReader : BinaryReader

在我的应用程序中,我得到:

【问题讨论】:

标签: c# .net encoding utf-8


【解决方案1】:

您无法按字节读取 UTF-8,因为单个字符可能占用多个字节。

参见How to convert byte[] to string?(首先将所有内容读入一个字节数组/列表)。

【讨论】:

  • 谢谢,工作:) 我正在使用的正确解决方案是:将所有字节推入 List,然后使用 Encoding.UTF8.GetString(list.ToArray()) 进行转换
猜你喜欢
  • 2013-05-11
  • 2020-07-17
  • 2011-08-16
  • 2012-09-11
  • 1970-01-01
  • 2017-02-04
  • 1970-01-01
  • 1970-01-01
  • 2014-06-09
相关资源
最近更新 更多