Convert String to Int & Int to String

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StringToLong
{
class StringToLong
{
private static int strToInt(string str)
{
int i = 0, num = 0;
bool isNeg = false;

int len = str.Length;

if (str[0] == '-')
{
isNeg = true;
i = 1;
}

while (i < len)
{
num *= 10;
num += (str[i++] - '0');
}
if (isNeg)
num *= -1;

return num;
}

private static string intToStr(int num)
{
int i = 0;
bool isNeg = false;

char[] temp = new char[10 + 1];

if (num < 0)
{
num *= -1;
isNeg = true;
}

//while (num != 0)
//{
// temp[i++] = (char)((num % 10) + '0');
// num /= 10;
//}

do
{
temp[i++] = (char)((num % 10) + '0');
num /= 10;

} while (num != 0);

StringBuilder sb = new StringBuilder();

if (isNeg)
sb.Append('-');

while(i > 0)
{
sb.Append( temp[--i]);
}
return sb.ToString();
}

private static long ConvertString(string str)
{
int len = str.Length;
bool blNegative = false;

int index = blNegative? 1:0;

if (str[0].Equals("-"))
{
blNegative = true;
}

long lnResult = 0;

do {
lnResult *= 10;
int i = str[index] - 48; //ASCII zero
if (i < 0 | i > 9)
throw new FormatException();

lnResult += i;
index++;
} while(len > index);

return blNegative? -lnResult:lnResult;
}

static void Main(string[] args)
{
string str1 = "3511";

Console.WriteLine(ConvertString(str1).ToString());

Console.WriteLine("{0} : {1}", str1, strToInt(str1).ToString());

str1 = "0";

Console.WriteLine("{0} : {1}", strToInt(str1), intToStr(strToInt(str1)));

Console.ReadLine();

}
}
}

Advertisements