Ascii Bytes Array To Int32 or Double

Posted by Michael Covelli on Stack Overflow See other posts from Stack Overflow or by Michael Covelli
Published on 2010-03-26T12:21:12Z Indexed on 2010/03/26 12:23 UTC
Read the original article Hit count: 554

Filed under:
|
|
|
|

I'm re-writing alibrary with a mandate to make it totally allocation free. The goal is to have 0 collections after the app's startup phase is done.

Previously, there were a lot of calls like this:

Int32 foo = Int32.Parse(ASCIIEncoding.ASCII.GetString(bytes, start, length));

Which I believe is allocating a string. I couldn't find a C# library function that would do the same thing automatically. I looked at the BitConverter class, but it looks like that is only if your Int32 is encoded with the actual bytes that represent it. Here, I have an array of bytes representing Ascii characters that represent an Int32.

Here's what I did

public static Int32 AsciiBytesToInt32(byte[] bytes, int start, int length)
{
     Int32 Temp = 0;
     Int32 Result = 0;
     Int32 j = 1;

     for (int i = start + length - 1; i >= start; i--)
     {
          Temp = ((Int32)bytes[i]) - 48;

          if (Temp < 0 || Temp > 9)
          {
               throw new Exception("Bytes In AsciiBytesToInt32 Are Not An Int32");
          }

          Result += Temp * j;
          j *= 10;
     }

     return Result;
}

Does anyone know of a C# library function that already does this in a more optimal way? Or an improvement to make the above run faster (its going to be called millions of times during the day probably). Thanks!

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET