Pro načítání a ukládání hex stringu z/do streamu můžete použít tyto funkce:
public static string LoadToHexString(Stream inputStream)
{
var sb = new StringBuilder();
using (inputStream)
{
while (true)
{
int b = inputStream.ReadByte();
if (b == -1)
{
break;
}
sb.AppendFormat("{0:X2}", b);
}
}
return sb.ToString();
}
public static void SaveHexString(Stream outputStream, string hexString)
{
using (outputStream)
{
if ((hexString.Length & 1) != 0)
{
throw new ArgumentException("Input must have even number of characters");
}
int length = hexString.Length / 2;
for (int i = 0, j = 0; i < length; i++)
{
int high = ParseNybble(hexString[j++]);
int low = ParseNybble(hexString[j++]);
outputStream.WriteByte((byte)((high << 4) | low));
}
}
}
private static int ParseNybble(char c)
{
if (c >= '0' && c <= '9')
{
return c - '0';
}
c = (char)(c & ~0x20);
if (c >= 'A' && c <= 'F')
{
return c - ('A' - 10);
}
throw new ArgumentException("Invalid nybble: " + c);
}
a jejich volání bude např.:
TextBox1.Text = LoadToHexString(File.OpenRead("C:\test.bin"));
SaveHexString(File.OpenWrite("C:\test.bin"), TextBox1.Text);
Pro převod byte[] na hex string a opačně budou obdobné funkce takto:
public static string ToHexString(byte[] data)
{
var sb = new StringBuilder(data.Length * 2);
foreach (byte b in data)
{
sb.AppendFormat("{0:X2}", b);
}
return sb.ToString();
}
public static byte[] ParseHexString(string hexString)
{
if ((hexString.Length & 1) != 0)
{
throw new ArgumentException("Input must have even number of characters");
}
int length = hexString.Length / 2;
byte[] ret = new byte[length];
for (int i = 0, j = 0; i < length; i++)
{
int high = ParseNybble(hexString[j++]);
int low = ParseNybble(hexString[j++]);
ret[i] = (byte)((high << 4) | low);
}
return ret;
}
private static int ParseNybble(char c)
{
if (c >= '0' && c <= '9')
{
return c - '0';
}
c = (char)(c & ~0x20);
if (c >= 'A' && c <= 'F')
{
return c - ('A' - 10);
}
throw new ArgumentException("Invalid nybble: " + c);
}
|