首页 / .NET / 正文

.NET[C#]如何将utf-8的字节数组byte[]转换成字符串string?

4205 发布于: 2018-01-01 读完约需6分钟

.NET[C#]如何将utf-8的字节数组byte[]转换成字符串string?

方式一、Encoding GetString

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

注:使用这种方式,如果这些字节有非ascii字符,就无法返回原始字节。

方式二、内存流

当你不清楚字节数组的编码时,一种常规的方式是使用内存流来实现:

static string BytesToStringConverted(byte[] bytes)
{
    using (var stream = new MemoryStream(bytes))
    {
        using (var streamReader = new StreamReader(stream))
        {
            return streamReader.ReadToEnd();
        }
    }
}

方式三、自定义扩展方法

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;
    }

}

方式四、UnicodeEncoding

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

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

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: .NET[C#]中如何循环列举枚举中的所有成员?

下一篇: .NET[C#]中如何反序列化一个动态的JSON对象?

本文永久链接码友网 » .NET[C#]如何将utf-8的字节数组byte[]转换成字符串string?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册