When I was finishing work on my robotic vehicle for TechEd 2008, I was in need for string to number conversion. Since the number parsing is not yet available in .NET Micro Framework, I’ll have to find some workaround.

My initial idea was to go with Jens Kühner’s implementation, but his source code was unavailable. You know the internet, everything is there - but not when you really need it. So, I have had to implement it on my own. Here is the result.

``````/// <summary>
/// Converts string to positive integer number
/// </summary>
/// <param name="value">Value in string</param>
/// <param name="result">Result as integer </param>
/// <returns>True if conversion succeeded</returns>
private bool StringToInt(string value, out int result)
{
result = 0;

int multiplier = 1;
int charValue = 0;

// go from end to begin
for (int i = value.Length - 1; i >= 0; i--)
{
// if character is number
if (CharToNumber(value[i], out charValue))
{
result += (multiplier * charValue);

// increse the multiplier
multiplier *= 10;
}
// test the negative value
else if (i == 0 && value[i] == '-')
{
result *= -1;
}
// otherwise die with false
else
{
result = 0;
return false;
}
}
return true;
}

/// <summary>
/// Converts char to integer
/// </summary>
/// <param name="value">Value in string</param>
/// <param name="result">Result as integer </param>
/// <returns>True if conversion succeeded</returns>
private bool CharToNumber(char character, out int result)
{
result = 0;
switch (character)
{
case '1': result = 1; break;
case '2': result = 2; break;
case '3': result = 3; break;
case '4': result = 4; break;
case '5': result = 5; break;
case '6': result = 6; break;
case '7': result = 7; break;
case '8': result = 8; break;
case '9': result = 9; break;
case '0': result = 0; break;
default:
return false;
}

return true;
}
``````

It’s a simple StringToInt() method with the same syntax as int.TryParse(). It returns true if the string is valid number and result argument filled with the converted value. Method accepts negative sign, but not spaces, dots etc..

``````int i;
if (StringToInt("-100", out i))
{
i *= 2;
Debug.Print(i.ToString());
}
else
{
Debug.Print("Not a number");
}
``````