Monday, January 23, 2006

Convert.ToInt32('0') not the same as Convert.ToInt32("0") (C#)

depending on your mileage and prior programming languages experience you might already be well aware of this issue.

...this wasn't my case, the other day we hit a bug with an algorithm that calculates a check digit, my colleage had translated the code from vbscript and made sure that it matched the VBScript version, but we were still getting incorrect check digits so I gave it a try debugging side by side with another version in Delphi

I found the bug in the first iteration

the code was something like:
char c=someString[someCounter];
int i = Convert.ToInt32(c);
total+=i;
...

turns out Convert.ToInt32(c) returns 48 and not 0 (for c='0') as we were expecting, this is really easy to fix once you know but can cause some really odd bugs

leason learned, next time I need to convert a char (that I know is a digit) to an int, I'll just use

char c = '0';
int i = c-48;

=o)

1 comment:

Anonymous said...

That "magic number" 48 is bad programming practice. Instead you should use something like Convert.ToInt32(theChar.ToString()), and it will work even if ASCII constraints aren't true in the future.