0

I have a problem when converting a char to hex value the code below works correctly when the char is a number but it's throw exception when the char is a latter

System.FormatException: 'Input string was not in a correct format

Code:

public byte[,] get_state(string plainText)
{
    char[] cplainText = plainText.ToCharArray();
    byte[,] state = new byte[4, 4];
    plainText = plainText.Remove(0, 2);

    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 4; j+=2)
        {
            string sub = plainText.Substring((i * 4 + j), 2);
            state[i, j] = Convert.ToByte(sub);
        }
    }

    return state;
}

The input string was "0x3243F6A8885A308D313198A2e0370734" and the exception across when the iteration of "F6"

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    Possible duplicate of [How do you convert a byte array to a hexadecimal string, and vice versa?](https://stackoverflow.com/questions/311165/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-and-vice-versa) – O. Jones Mar 30 '19 at 12:45
  • Use following to convert hex number : byte.Parse(sub, System.Globalization.NumberStyles.HexNumber); – jdweng Mar 30 '19 at 12:51

1 Answers1

0
Convert.ToByte();

It says in the overload that it only accepts numbers in string format.

You have to think about if you use the right method, or convert it beforehand.

  • "_It says in the overload that it only accepts numbers in string format._" Well, if you look closely enough, you will notice that Convert.ToByte() has an overload that allows specifying the base of the number (like 16 for hexadecimal). So, yes it is correct that Convert.ToByte only accepts numbers in string format, but this includes hex numbers as well... –  Mar 30 '19 at 14:22