主要用于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,"-"));
}
}