using System;
using System.Text;
namespace EAS.Distributed
{
static class Bytes
{
///
/// 将指定的字节数组转换为HEX字符串。
///
/// 要转换的字节数组。
/// 返回已经转换的字节数组字符串。
public static string ToHex(this byte[] buffer)
{
if (buffer == null)
return null;
if (buffer.Length == 0)
return string.Empty;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < buffer.Length; i++)
{
sb.Append(buffer[i].ToString("X2"));
}
return sb.ToString();
}
///
/// 将格式为“XXXX”的字符串。(其中“xx”为每一个字节的十六进制表示)转换为相应的字节数组。
///
/// 要转换的字符串。
/// 返回转换后的字节数组。
/// s 为空引用。
/// 字符串 s 格式无效。
/// 如果 s 为空字符串,则返回长度为 0 的字节数组。
public static byte[] FromHex(this string s)
{
if (s == null)
throw new ArgumentNullException("s", "要转换的字符串不能是空引用。");
if (s.Trim() == string.Empty)
return new byte[0];
if (s.Length % 2 != 0)
throw new ArgumentNullException("s", "要转换的字符串长度必须为2的整数倍。");
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i < buffer.Length; i++)
{
string Text = s.Substring(i * 2, 2);
try
{
buffer[i] = byte.Parse(Text, System.Globalization.NumberStyles.AllowHexSpecifier);
}
catch (System.FormatException exc)
{
throw new System.ArgumentException("无效的字节字符串格式。", "s", exc);
}
}
return buffer;
}
}
}