|
/// <summary>
/// 二进制扩展工具类
/// </summary>
public static class BytesExtensions
{
/// <summary>
/// 二进制转16进制字符串
/// </summary>
/// <param name="input">二进制数组</param>
/// <returns>返回16进制字符串</returns>
public static string ToStr16BinaryFromBuffer(this byte[] input)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in input)
sb.AppendFormat("{0:x2}", b);
return sb.ToString();
}
/// <summary>
/// 转换为数据流
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static Stream ToStream(this byte[] input)
{
return new MemoryStream(input);
}
/// <summary>
/// 16进制字符串转换为二进制数据
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public static byte[] ToBufferFromStr16Binary(this string target)
{
Requires.NotNull(target, "target");
var buffer = new byte[target.Length / 2];
var index = 0;
var saveIndex = 0;
while (index < target.Length)
{
buffer[saveIndex] = Convert.ToByte(target.Substring(index, 2), 16);
index += 2;
saveIndex++;
}
return buffer;
}
}
|
|