我有一个字节[]数组,从一个文件加载,我碰巧知道包含UTF-8。

在一些调试代码中,我需要将其转换为字符串。是否有一个单行程序可以做到这一点?

在表面之下,它应该只是一个分配和一个memcopy,所以即使没有实现,也应该是可能的。


当前回答

还有一个类UnicodeEncoding,使用起来非常简单:

ByteConverter = new UnicodeEncoding();
string stringDataForEncoding = "My Secret Data!";
byte[] dataEncoded = ByteConverter.GetBytes(stringDataForEncoding);

Console.WriteLine("Data after decoding: {0}", ByteConverter.GetString(dataEncoded));

其他回答

我在这篇文章中看到了一些答案,这可能被认为是完整的基础知识,因为我在c#编程中有几种方法来解决相同的问题。唯一需要考虑的是纯UTF-8和带有BOM的UTF-8之间的区别。

Last week, at my job, I needed to develop one functionality that outputs CSV files with a BOM and other CSV files with pure UTF-8 (without a BOM). Each CSV file encoding type will be consumed by different non-standardized APIs. One API reads UTF-8 with a BOM and the other API reads without a BOM. I needed to research the references about this concept, reading the "What's the difference between UTF-8 and UTF-8 without BOM?" Stack Overflow question, and the Wikipedia article "Byte order mark" to build my approach.

最后,我的c#编程的UTF-8编码类型(BOM和纯)需要类似于下面的例子:

// For UTF-8 with BOM, equals shared by Zanoni (at top)
string result = System.Text.Encoding.UTF8.GetString(byteArray);

//for Pure UTF-8 (without B.O.M.)
string result = (new UTF8Encoding(false)).GetString(byteArray);

另外:

 var byteStr = Convert.ToBase64String(bytes);

用于将从文件中读取的字节数组byteArrFilename转换为纯ASCII c风格以零结尾的字符串的LINQ一行程序如下:

String filename = new String(byteArrFilename.TakeWhile(x => x != 0)
                              .Select(x => x < 128 ? (Char)x : '?').ToArray());

我用'?'作为非纯ASCII的默认字符,当然,这是可以改变的。如果您想确保可以检测到它,只需使用'\0',因为开始时的TakeWhile确保以这种方式构建的字符串不可能包含来自输入源的'\0'值。

除了选择的答案,如果你使用。net 3.5或。net 3.5 CE,你必须指定解码的第一个字节的索引,以及解码的字节数:

string result = System.Text.Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);

据我所知,没有一个给出的答案保证正确的行为与空终止。直到有人告诉我不同的,我写了自己的静态类处理以下方法:

// Mimics the functionality of strlen() in c/c++
// Needed because niether StringBuilder or Encoding.*.GetString() handle \0 well
static int StringLength(byte[] buffer, int startIndex = 0)
{
    int strlen = 0;
    while
    (
        (startIndex + strlen + 1) < buffer.Length // Make sure incrementing won't break any bounds
        && buffer[startIndex + strlen] != 0       // The typical null terimation check
    )
    {
        ++strlen;
    }
    return strlen;
}

// This is messy, but I haven't found a built-in way in c# that guarentees null termination
public static string ParseBytes(byte[] buffer, out int strlen, int startIndex = 0)
{
    strlen = StringLength(buffer, startIndex);
    byte[] c_str = new byte[strlen];
    Array.Copy(buffer, startIndex, c_str, 0, strlen);
    return Encoding.UTF8.GetString(c_str);
}

使用startIndex的原因是在我正在处理的示例中,我需要将byte[]解析为一个以null结尾的字符串数组。在简单的情况下,可以安全地忽略它