C# 多种输出字节数组的方法

跟计算机打交道难免经常需要输出一个字节数组。

今天这篇文章就讲讲怎样输出一个字节数组在.NET下的各种方法:

string BitConverter.ToString(byte[])方法。(有重载支持字节数组的部分输出)

举例:

Console.WriteLine(BitConverter.ToString(new byte[] { 1, 3, 54, 123, 199, 200, 215, 255 }));

输出为:

01-03-36-7B-C7-C8-D7-FF

缺点是无法自定义中间的间隔符(或者去掉中间的间隔符)。

如果需要修改(或去掉)间隔符的话,最简单的方法就是直接替换:

Console.WriteLine(BitConverter.ToString(new byte[] { 1, 13, 54 }).Replace("-", ","));

不过还是自己定义一个比较好:

//自定义输出字符数组方法
static string GetBytesString(byte[] bytes, int index, int count, string sep)
{
    var sb = new StringBuilder();
    for (int i = index; i < count - 1; i++)
    {
        sb.Append(bytes[i].ToString("X2") + sep);
    }
    sb.Append(bytes[index + count - 1].ToString("X2"));
    return sb.ToString();
}

上面这个GetBytesString方法看起来简单易懂了,当然还有其他方法使它更简洁,看看下面这个修改后的GetBytesString,用String.Join和LINQ,一句话搞定上面的代码:

//自定义输出字符数组方法(更简洁)
static string GetBytesString(byte[] bytes, int index, int count, string sep)
{
    return String.Join(sep, bytes.Skip(index).Take(count).Select(b => b.ToString("X2")));
}

上面提到了LINQ,那么就用纯LINQ来试试解决这个问题,看下面代码(有点可拍):

//自定义输出字符数组方法(纯LINQ。除了字符串连接,格式化,返回字符串,这些LINQ不可能做到的)
static string GetBytesString(byte[] bytes, int index, int count, string sep)
{
    return new string(bytes.Skip(index).Take(count - 1).Select(b => b.ToString("X2") + sep).SelectMany(i => i.ToCharArray()).Concat(bytes.Skip(index + count - 1).Take(1).SelectMany(b => b.ToString("X2").ToCharArray())).ToArray());
}

上面这些代码都可以正确输出结果,比如:

Console.WriteLine(GetBytesString(new byte[] { 34, 5, 1, 13, 54 }, 2, 3, " = "));

输出:01 = 0D = 36

最后还可以通过继承.NET中的IFormatProvider和ICustomFormatter来自定义格式器来提供对字节数组的输出,通过格式字符串来指定间隔符,最后使用String.Format来定义自定义格式器,格式字符串从而将字节数组输出,代码:

/// <summary>
/// 自定义格式器
/// </summary>
class MyFormatter : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatterType)
    {
        if (formatterType == typeof(ICustomFormatter))
            return this;
        return null;
    }
    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        //判断是字节数组,并根据格式字符串来返回相应结果
        if (arg is byte[])
            return GetBytesString((byte[])arg, format);
        throw new NotSupportedException();
    }

    static string GetBytesString(byte[] bytes, string sep)
    {
        return String.Join(sep, bytes.Select(b => b.ToString("X2")));
    }

}

public class Program
{
    static void Main(string[] args)
    {
        var bytes = new byte[] { 34, 13, 43, 92, 222 };
        //使用String.Format来定义一个格式器(IFormatProvider)
        Console.WriteLine(String.Format(new MyFormatter(), "{0: =|= }\n{1:-}\n{2}", bytes, bytes, bytes));
    }
}

输出:

22 =|= 0D =|= 2B =|= 5C =|= DE
22-0D-2B-5C-DE
220D2B5CDE

结果都正确。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明仔丶

谢谢大家

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值