atoi again

Hello all

I'm trying to do the equivalent of the easy C code here
int someNum = atoi( someArray[20] );
Where someArray is an array of characters.

You would think that this would work:

someArray[20] = '9';
int someNum = Convert.ToInt32(someArray[20]);
//but someNum = 57 since ASCII 9 = 57.

So I am using this:
int arm2 = Convert.ToInt32(new string(rec,84,1));

Is there an easier (faster) way of doing this?  I am doing some reading/writing ascii files that reads in a line and pulls numbers from it using these converts.  I am trying to cut down on the time it takes for it to read all the stuff from the file.

Who is Participating?
gregoryyoungConnect With a Mentor Commented:
int val;
for(i-=0;i<someArray.Length;i++) {
    val = val * 10 + (int) someArray[i];

this will work on a char array of appropriate size (simple modification to support whatever sized array)

string foo = new string(someArray);
int bar = int.Parse(foo);

works as well ...
Unless you have to have a character array, why not use StreamReader to read the file into a strings.

NTACAuthor Commented:
cookre:  the problem with that is the file is over 1Gb in size, and the performance between StreamReader vs BufferedStream(using a FileStream) is significant.  I think it has to do with the overhead of the strings.  

greg:  the reason I didn't use my own atoi function is whitespaces.  Sometimes there are whitespaces and the c version of atoi ignores them--but I didn't put it in my function.  I'll do some performance comparisions and see what happens.

ignoring whitespace is pretty easy ... just put in a if()
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.