Looking at this from the point of view of conversion of a string in hex format to byte[] and conversion of byte[] to hex format string with the requirement to optionally use a format where hex bytes are separated by dashes:
private static string dash = "-";
private static byte[] ByteAryFromHexString(string hx)
{
if (hx.Contains(dash)) hx = hx.Replace(dash, "");
hx = hx.ToUpperInvariant();
byte[] result = new byte[hx.Length / 2];
for (int i = 0; i < result.Length; i++)
{
result[i] = Convert.ToByte(hx.Substring(i*2,2), 16);
}
return result;
}
private static string HexStringFromByteArray(byte[] bytes, bool withDash = false)
{
var result = BitConverter.ToString(bytes);
if (withDash) return result;
return (result.Replace(dash, ""));
}
Test:
string hx1 = @"AA-55-55-55-15-55-6A-AA-FF-FF-00-00-FF-FF-00-10-00-06-08-8F-00-E2-A0-80-08-D3";
string hx2 = @"AA55555515556AAAFFFF0000FFFF00100006088F00E2A08008D3";
private void Test()
{
byte[] b1 = ByteAryFromHexString(hx1);
byte[] b2 = ByteAryFromHexString(hx2);
string enc1 = Encoding.UTF8.GetString(b1);
string enc2 = Encoding.UTF8.GetString(b2);
bool i1 = enc1 == enc2;
string s1 = HexStringFromByteArray(b1, true);
string s2 = HexStringFromByteArray(b2, false);
bool i2 = s1 =!= s2;
}
Note: Hex format String to Byte[] conversion is one place .NET doesn't really offer a really fast built-in conversion. There is a great deal of debate about the fastest way to achieve that: you can find extensive discussions, and performance measurements, of various methods on threads on StackOverFlow like this one: [
^].