using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace System
{
/// <summary> 十六进制 转换器 </summary>
public class HexConverter
{
private const int RADIX = 16;
private static readonly Regex PATTERN = new Regex("([0123456789ABCDEF]{2})+", RegexOptions.IgnoreCase);
private static byte[] OutputBytes(string hex)
{
var list = new List<byte>();
foreach (Match match in PATTERN.Matches(hex))
{
foreach (Capture capture in match.Groups[1].Captures)
{
list.Add(Convert.ToByte(capture.Value, RADIX));
}
}
return list.ToArray();
}
private static string OutputHexString(byte[] bits, string separator)
{
var result = new StringBuilder();
for (var i = 0; i < bits.Length; i++)
{
if (0 != i) result.Append(separator ?? string.Empty);
result.Append(bits[i].ToString("X2"));
}
return result.ToString();
}
#region 10 进制 -> 16 进制
/// <summary> String -> Hex String </summary>
public static string GetHex(string str, string separator = null)
{
return GetHex(str, Encoding.Default, separator);
}
/// <summary> String -> Hex String </summary>
public static string GetHex(string str, Encoding encode, string separator = null)
{
if (!string.IsNullOrEmpty(separator))
{
str = str.Replace(separator, string.Empty);
}
var bits = encode.GetBytes(str);
return OutputHexString(bits, separator);
}
/// <summary> Byte -> Hex String </summary>
public static string GetHex(byte bit)
{
return bit.ToString("X2");
}
/// <summary> Byte[] -> Hex String </summary>
public static string GetHex(byte[] bits, string separator = null)
{
return "-" == separator ? BitConverter.ToString(bits) : BitConverter.ToString(bits).Replace("-", separator ?? string.Empty);
}
#endregion
#region 16 进制 -> 10 进制
/// <summary> Hex String -> Byte[] </summary>
public static byte[] GetBytes(string hex, string separator = null)
{
if (string.IsNullOrEmpty(separator))
{
return OutputBytes(hex);
}
else
{
var temp = hex.Split(separator);
var result = new byte[temp.Length];
for (var i = 0; i < temp.Length; i++)
{
result[i] = Convert.ToByte(temp[i], RADIX);
}
return result;
}
}
/// <summary> Hex String -> String </summary>
public static string ToString(string hex, string separator = null)
{
return ToString(hex, Encoding.Default, separator);
}
/// <summary> Hex String -> String </summary>
public static string ToString(string hex, Encoding encode, string separator = null)
{
if (!string.IsNullOrEmpty(separator))
{
hex = hex.Replace(separator, string.Empty);
}
var data = OutputBytes(hex);
return encode.GetString(data);
}
#endregion
}
}