0

I'm trying to parse a user-entered hex string so that I can emit a correctly formatted version to disk.

The "correct" format, in this case, looks like A1 F5 E1 C9 - space separated bytes with uppercase hex letters. However, the user input might not have spaces (A1F5E1C9), might have line breaks (A1 F5\nE1 C9), might have leading or trailing space (\nA1 F5 E1 C9\n\n\n), and might have dashes instead of spaces (A1-F5-E1-C9). It might have any combination of those variations, as well. Some of the numbers this will be used on are public keys, which can be quite long.

How can I handle reformatting this? The two semi-solutions I've been able to come up with so far are

BigInteger.Parse(value.Trim()
                      .Replace(" ", "")
                      .Replace(@"\n", "")
                      .Replace(@"\r", ""), 
                 NumberStyles.HexNumber).ToString("X2");

which still doesn't produce a spaced-out string, or

string.Join(" ", Regex.Matches(a, @"([0-9A-Fa-f]{2})")
                      .Cast<Match>()
                      .Select(x => x.Captures[0].Value.ToUpper()))

which does work, but feels like it has a lot of extraneous overhead (Regex, LINQ).

Is the second method actually the best way to do this? Is there something obvious I'm overlooking?

Bobson
  • 13,498
  • 5
  • 55
  • 80
  • Either will work. If you're concerned about performance for some reason you can create an extension method that uses something like a StringBuilder to copy the non-whitespace characters to a new buffer then returns that new buffer, and throws if it encounters an invalid input character. – Eric J. Mar 14 '16 at 21:59

1 Answers1

0

I don't know how long the hex strings can be in your case, but you can convert your string (after cleaning it out of not needed characters) to byte array and use BitConverter class to convert it to proper string. It is described e.g. here: How do you convert Byte Array to Hexadecimal String, and vice versa?

BitConverter class is described here: https://msdn.microsoft.com/en-us/library/system.bitconverter(v=vs.110).aspx

Community
  • 1
  • 1
Marcin Cuprjak
  • 674
  • 5
  • 6