Convert a String to long without using C#’s built in function?

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

namespace StringToLong
{
class StringToLong
{
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 = "35111111111";

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

Console.ReadLine();

}
}
}

In Java

public static void main(String[] args) {
String s = "35";
long ans = parse(s);
}

public final static long parse(CharSequence d) {
int l = d.length();
boolean n= d.charAt(0) == '-';
long v = 0;
int p = n?1:0;
do {
v *= 10;
int i = d.charAt(p) - 48;
if (i < 0 | i > 9)
throw new NumberFormatException(d+"");
v += i;
p++;
} while (l > p);
return n?-v:v;
}

Advertisements