sharp-extensions/HexString.cs

61 lines
1.4 KiB
C#

using System;
using System.Text;
namespace sharp.extensions
{
public class HexString
{
public static byte[] toBytes(char[] hexstring){
return toBytes(new String(hexstring));
}
public static byte[] toBytes(string hexstring)
{
byte[] bytes = new byte[hexstring.Length >> 1];
for (int n = 0; n < hexstring.Length >> 1;n++){
bytes[n] = Convert.ToByte(hexstring.Substring(n << 1, 2), 16);
}
return bytes;
}
public static String toString(byte[] bytes)
{
return BitConverter.ToString(bytes).Replace("-", String.Empty);
}
public static String toString(byte[] bytes,int groupsize)
{
StringBuilder sb = new StringBuilder();
String hs = BitConverter.ToString(bytes).Replace("-", String.Empty);
int n = hs.Length / (groupsize * 2);
for (int i = 0; i < n;i++){
sb.Append(hs.Substring(n * (groupsize * 2), (groupsize * 2)));
sb.Append(" ");
}
return sb.ToString();
}
public static String toString(byte[] bytes, int groupsize,int linewidth)
{
StringBuilder sb = new StringBuilder();
String hs = BitConverter.ToString(bytes).Replace("-", String.Empty);
int n = hs.Length / (groupsize * 2);
for (int i = 0; i < n; i++)
{
sb.Append(hs.Substring(i * (groupsize * 2), (groupsize * 2)));
if ((i!=0)&&((i % linewidth)==(linewidth-1))){
sb.AppendLine();
} else {
sb.Append(" ");
}
}
return sb.ToString();
}
}
}