-1

I Got an Error while compiling this code for my encrypting class, it say "Exception thrown: 'System.FormatException' in mscorlib.dll"

public static byte[] StringToByteArray(String hex)
{
    int NumberChars = hex.Length;
    byte[] bytes = new byte[NumberChars / 2];
    for (int i = 0; i < NumberChars; i += 2)
        bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
    return bytes;
}

Can anyone help?

ViVi
  • 4,339
  • 8
  • 29
  • 52
Richard
  • 71
  • 1
  • 12

2 Answers2

1

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;
    }
}
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
-1

I tried to run program with your code and seems like they've no problem so far. Unless "String hex" contains any character that's not hex string (0-9, A-F), It'll occurred with the same error as you. Make sure that your input parameter aren't contains any character that isn't hex string.

Nagato
  • 9
  • 2
  • Your answer comes down to either "non-repro" or "check your input". That's a reason to close a question, not to answer it. – CodeCaster Dec 21 '16 at 09:54
  • Since I can't comment the post so I'm replying as answer instead. I'm really sorry if its bothering anyone. – Nagato Dec 21 '16 at 10:17