StringToByteArray () exception in C # 2.0

I am using StringToByteArray () on VS2005. But throw an exception. Could you tell me more information about this?

Exception warning ** An unhandled exception of type "System.FormatException" occurred in the mscorlib.dll file

Additional Information: Could not find recognizable digits. **

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

    static void Main()
    {
            byte[] myByte = new byte[2];
        myByte = StringToByteArray("0x0");
    }
+3
source share
2 answers

You need to either reset "0x" from the beginning of the line you are going to, or start the loop forwith int i = 2;. You also allocate an array to your method. You also do not need to do this Main.

+3
source

Well, you have the option of dividing by the null exception ...

, , , , 0x, .

+1

All Articles