I'm going to depart from the other answers and focus on this bit:
Am I missing some elegant method?
Do you consider Regex to be elegant? You could reduce the amount of code required at the cost of performance. Take the following Regex expression:
(?<=\G..)(?!$)
Broken down:
(?<= # Look-behind that won't actually be captured
\G # Zero-width assertion
.. # Match exactly two characters
)(?!$) # Do not match an empty group at the end of the string
Then it's just a matter of transforming the string array into a collection of characters and joining them all back together. Using Linq's Select
and the string.Join
method, this can be done quickly.
A short implementation may look like:
string HexStringToString(string hexString)
{
string[] hexValues = Regex.Split(hexString, "(?<=\\G..)(?!$)");
var characters = hexValues.Select(hex => (char)Convert.ToByte(hex, 16));
return string.Join(string.Empty, characters);
}
Elegant? Sure. You could even do it all on a single line:
string HexStringToString(string hexString)
{
return string.Join("", Regex.Split(hexString, "(?<=\\G..)(?!$)").Select(x => (char)Convert.ToByte(x, 16)));
}
But elegance is never more valuable than readability and maintainability.
As @CodesInChaos said, your method is doing multiple things and should be split apart. I would even break out the functionality of separating a string into its own method, perhaps as an extension method off of the String
class.
static
as it appears that it doesn't access any class instance data. Further, it looks like an excellent candidate to be an extension method (simply change the parameter to readthis string HexString
after making the methodstatic
). \$\endgroup\$