I am practicing StringToByteArray() on VS2005. But throw exception. Could you please tell me more information about it?
Exception alert **An unhandled exception of type ‘System.FormatException’ occurred in mscorlib.dll
Additional information: Could not find any 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");
}
You either need to drop the “0x” from the start of the string you pass in, or start your
forloop withint i = 2;. Also you’re allocating the array in your method. You don’t need to do itMainas well.