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

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

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


当前回答

将字节[]转换为字符串似乎很简单,但任何一种编码都有可能把输出字符串弄乱。这个小函数只是工作,没有任何意想不到的结果:

private string ToString(byte[] bytes)
{
    string response = string.Empty;

    foreach (byte b in bytes)
        response += (Char)b;

    return response;
}

其他回答

BitConverter类可用于将字节[]转换为字符串。

var convertedString = BitConverter.ToString(byteAttay);

BitConverter类的文档可以在MSDN上打印。

另外:

 var byteStr = Convert.ToBase64String(bytes);

应用(字节)b to弦(“x2”),Outputs b4b5dfe475e58b67

public static class Ext {

    public static string ToHexString(this byte[] hex)
    {
        if (hex == null) return null;
        if (hex.Length == 0) return string.Empty;

        var s = new StringBuilder();
        foreach (byte b in hex) {
            s.Append(b.ToString("x2"));
        }
        return s.ToString();
    }

    public static byte[] ToHexBytes(this string hex)
    {
        if (hex == null) return null;
        if (hex.Length == 0) return new byte[0];

        int l = hex.Length / 2;
        var b = new byte[l];
        for (int i = 0; i < l; ++i) {
            b[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
        }
        return b;
    }

    public static bool EqualsTo(this byte[] bytes, byte[] bytesToCompare)
    {
        if (bytes == null && bytesToCompare == null) return true; // ?
        if (bytes == null || bytesToCompare == null) return false;
        if (object.ReferenceEquals(bytes, bytesToCompare)) return true;

        if (bytes.Length != bytesToCompare.Length) return false;

        for (int i = 0; i < bytes.Length; ++i) {
            if (bytes[i] != bytesToCompare[i]) return false;
        }
        return true;
    }

}

定义:

public static string ConvertByteToString(this byte[] source)
{
    return source != null ? System.Text.Encoding.UTF8.GetString(source) : null;
}

使用:

string result = input.ConvertByteToString();

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

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

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