C# Hex工具类(可用于mac转化)

主要用于string 与 bytes的 十六进制互转

using System;
using System.Text;

    public static class HexUtils{
        /// <summary>
        /// 字符串hex转bytes 可处理Mac
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="placeLength">多少位为一个hex字符串</param>
        /// <param name="placeholder">如果有分隔符则传入</param>
        /// <returns></returns>
        public static byte[] ToHexBytes(this string str, int placeLength = 1, string placeholder = null)
        {
            string s;
            if (placeholder != null || !placeholder.Equals(""))
            {
                s = str.Replace(placeholder, "");
            }
            else
            {
                s = str;
            }
            int l = s.Length / placeLength;
            byte[] hex = new byte[l];
            for (int i = 0; i < l; i++)
            {
                hex[i] = Convert.ToByte(Convert.ToInt32(s.Substring(i * placeLength, placeLength), 16));
            }
            return hex;
        }
        /// <summary>
        /// bytes字节组转Hex字符串,支持定长 与 分隔符
        /// </summary>
        /// <param name="b">Hex字节组</param>
        /// <param name="placeLength">多少个字节为一个Hex数字</param>
        /// <param name="placeholder">分隔符</param>
        /// <returns></returns>
        public static string ToHexString(this byte[] b, int placeLength = 1, string placeholder=null) {
            string format = "{0}";
            bool usePlace = placeholder != null && !placeholder.Equals("");
            if (usePlace)
            {
                format = "{0}" + placeholder; 
            }
            StringBuilder sb = new StringBuilder();
            int l = b.Length / placeLength;
            byte[] cache=new byte[placeLength];
            for (int i = 0; i <l ; i++)
            {
                for (int j = 0; j < placeLength; j++)
                {
                    cache[j] = b[i * placeLength + j];
                }
                sb.Append(string.Format(format, Convert.ToHexString(cache)));
            }
            if (usePlace)
            {
                sb.Remove(sb.Length - 1, 1);
            }
            return sb.ToString();
        }
    }

使用方法:直接将工具类放到工程中即可直接使用,参照下面代码

using System;
using System.Text;
class Program
    {
        static void Main(string[] args)
        {
            string mac = "AA-BB-CC-DD-EE-FF";
            byte[] b = mac.ToHexBytes(2,"-");
//          Console.WriteLine(Convert.ToHexString(b));
            Console.WriteLine(b.ToHexString(1,"-"));
        }
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值