【问题标题】:Decode zero-terminated UTF-8 string from any position in a byte array从字节数组中的任何位置解码以零结尾的 UTF-8 字符串
【发布时间】:2013-02-24 13:24:22
【问题描述】:

我正在FCL 中寻找一种类似于Encoding.UTF8.GetString(bytes, index, count) 的方法,但它不需要count 参数,而是假定给定索引处的字符串以空值结尾。

我将我当前的解决方案作为答案发布(见下文),但我很想知道是否有人知道更优雅或性能更好的方法。

【问题讨论】:

  • 我不知道 .NET Framework 中有任何方法可以处理以 0 结尾的 UTF-8 字符串。 Marshal Class 适用于以 0 结尾的字符串,但不进行 UTF-8 转换; UTF8Encoding Class 总是需要一个长度。

标签: .net string utf-8 bytearray decode


【解决方案1】:

我已经写了自己的方法,因为我在 FCL 中没有找到:

using System.Text;

string GetZeroTerminatedUTF8StringAt(byte[] bytes, int index)
{
    int zeroTerminatorIndex = Array.IndexOf<byte>(bytes, value: 0, startIndex: index);
    if (zeroTerminatorIndex >= index)
    {
        return Encoding.UTF8.GetString(bytes, index, count: zeroTerminatorIndex - index);
    }
    else
    {
        throw new ArgumentOutOfRangeException("index", "No zero-terminator found.");
    }
}

虽然这可行,但它有一个小问题:假设除'\0' 之外的任何字符都不会在UTF-8 编码中包含0 字节。虽然情况确实如此,但如果将该假设完全封装在 Encoding.UTF8 类中会更好。

【讨论】:

    猜你喜欢
    • 2013-05-11
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 2022-11-12
    • 2020-09-15
    • 2021-08-28
    相关资源
    最近更新 更多