Reputation: 427
As the title implies, I'm getting "An unhandled exception of type 'System.FormatException'" style message. Need some help figuring out why. I'm reading in a file that has a hex value I need to parse. The value I'm reading it could look something like this "0x12345678" (4 bytes in length).
The first byte (note this is little endian) is 'BE' and I can get that no problem. My issue is then trying to take the next three bytes and convert that into a human readable int. (Long story, but the program that generates the output I'm parsing takes a human readable decimal number and converts it to this LE nonsense.)
string parmVal = lineF.Substring((pos + length)); // this is "0x12345678"
string hexID = parmVal.Substring(2, 2); // stores '12'
byte[] testID = new byte[4];
testID[0] = Convert.ToByte(parmVal.Substring(4, 2)); <----error here
testID[1] = Convert.ToByte(parmVal.Substring(6, 2));
testID[2] = Convert.ToByte(parmVal.Substring(8, 2));
testID[3] = Convert.ToByte(0);
decimalID = int.Parse(hexID, System.Globalization.NumberStyles.HexNumber); // stores 18 (0x12)
testIDNumber = BitConverter.ToInt32(testID,0); // stores 345678
Interestingly, in the code I later output these values to a CSV file, and the values I print out look correct, even though its throwing the exception. I tried reading in the last 3 bytes the same way as the first by, but then when I do the int.Parse() on it, it gets its endian-ness backwards. Where I'd want it to convert 0x"785634", its converting 0x"345678".
Upvotes: 1
Views: 605
Reputation: 154
Try to specify base in Convert.ToByte call.
In your case it has to be:
testID[0] = Convert.ToByte(parmVal.Substring(4, 2), 16);
Upvotes: 1