Most likely the input is invalid. A hex string can only contain digits and characters between A and F.
Using the string A3AEEEF4
with the following code returns four bytes:
var bytes=StringToByteArray("A3AEEEF4");
Console.WriteLine("Length {0}. Content: {1}", bytes.Length,String.Join("-",bytes));
---------
> Length 4. Content: 163-174-238-244
The string AZAEEEF4
though isn't a valid hex string because the second letter is Z
. This will raise a FormatException
with the message Additional non-parsable characters are at the end of the string.
In fact, this is the correct exception for this situation. This is indeed a malformed hex string.
You could add exception handling to the method to return the character pair that caused the error, eg:
byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
{
var pair=hex.Substring(i, 2);
try
{
bytes[i / 2] = Convert.ToByte(pair, 16);
}
catch (FormatException exc)
{
throw new FormatException($"Invalid pair {pair} at {i}", exc);
}
return bytes;
}
or you can use Byte.TryParse to avoid throwing two exceptions:
byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
{
var pair=hex.Substring(i, 2);
if (!byte.TryParse(pair, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
out bytes[i / 2]))
{
throw new FormatException($"Invalid pair {pair} at {i}");
}
return bytes;
}
}