C#字节数组操作扩展类

在处理字节数组时,经常遇到一些业务相关有趣的问题,每次都需要重新写一些小方法去这样转换,那样转换。索性直接写成工具类,此文章供大家一起学习,没有封装好的地方,请多多指教!

/// <summary>
/// 字节数组操作扩展类
/// </summary>
public static class ByteUtil
{
    internal static byte[] AsciiBytes(string s)
    {
        byte[] bytes = new byte[s.Length];
        for (int i = 0; i < s.Length; i++)
        {
            bytes[i] = (byte)s[i];
        }
        return bytes;
    }

    internal static byte[] HexToByteArray(this string hexString)
    {
        byte[] bytes = new byte[hexString.Length / 2];
        for (int i = 0; i < hexString.Length; i += 2)
        {
            string s = hexString.Substring(i, 2);
            bytes[i / 2] = byte.Parse(s, NumberStyles.HexNumber, null);
        }
        return bytes;
    }

    internal static string ByteArrayToHex(this byte[] bytes)
    {
        var builder = new StringBuilder(bytes.Length * 2);
        foreach (byte b in bytes)
        {
            builder.Append(b.ToString("X2"));
        }
        return builder.ToString();
    }

    internal static string ByteArrayToHex(this byte[] bytes, int len)
    {
        return ByteArrayToHex(bytes).Substring(0, len * 2);
    }

    internal static byte[] RepeatByte(byte b, int count)
    {
        byte[] value = new byte[count];
        for (int i = 0; i < count; i++)
        {
            value[i] = b;
        }
        return value;
    }

    internal static byte[] SubBytes(this byte[] bytes, int startIndex, int length)
    {
        byte[] res = new byte[length];
        Array.Copy(bytes, startIndex, res, 0, length);
        return res;
    }

    internal static byte[] XOR(this byte[] value)
    {
        byte[] res = new byte[value.Length];
        for (int i = 0; i < value.Length; i++)
        {
            res[i] ^= value[i];
        }
        return res;
    }

    internal static byte[] XOR(this byte[] valueA, byte[] valueB)
    {
        int len = valueA.Length;
        byte[] res = new byte[len];
        for (int i = 0; i < len; i++)
        {
            res[i] = (byte)(valueA[i] ^ valueB[i]);
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值