Quote:
|
Originally Posted by punt59
Not a biggie, but the above code snippet I believe makes two assumptions (I do not profess to be versed in C#).
1. That the 0x occurs at the very beggining of the string. That there is no other whitespace in the string leading up to it. To address, one would adjust the Substring() call to use the index returned by the IndexOf() call.
2. It also assumes that one will never enter 0X instead of 0x.
These assumptions are probably valid 99% of the time, so I am sure one is probably making fine making these assumptions.
|
Well... if you were working with data that you could not verify as being valid ahead of time..
Code:
public static int ConvertHexToDecimal(string hexNumber)
{
hexNumber = hexNumber.Trim().ToLower();
int intStart = hexNumber.IndexOf("0x");
if (intStart > -1)
{
intStart += 2;
hexNumber = hexNumber.Substring(intStart, hexNumber.Length - intStart);
}
return Int32.Parse(hexNumber, System.Globalization.NumberStyles.AllowHexSpecifier);
}
That is a little less trusting of the input. It worked with the following cases:
Code:
Pre-Conversion: "0X411901"
Post-Conversion: 4266241
Pre-Conversion: " 0x7F00FF00"
Post-Conversion: 2130771712
Pre-Conversion: "sometext 0X04"
Post-Conversion: 4
Pre-Conversion: " 0x12345678"
Post-Conversion: 305419896
If anyone tries to pass something even worse through this method, they're probably better off receiving an exception.