R@M3$H.NBlog

[STRING] Convert Integer to String itoa()

16 September, 2013 - 1 min read

// val: integer that needs to be converted to string representation
// destBuffer: buffer where the output string will be written
// radix: is the radix of the numbering system (10 for decimal, 16 for Hexadecimal,
// 2 for binary)

char * my_itoa(int val, char * destBuffer, int radix)
{
   if(val == 0)
   {
      destBuffer = "0";
      return destBuffer;
   }

   bool isNeg = false;
   // if input integer is negative set the isNeg flag and make it positive
   // we will do the conversion using the absolute value and then append the
   // the - sign in the end
   if(val < 0)
   {
      isNeg = true;
      val *= -1; 
   }

   char *currentDest = destBuffer;

   while(val > 0)
   {
     int digit = val % radix;
     val /= radix;
     *currentDest = (char) (digit + '0');
     currentDest++;
   }

   if(isNeg)
   {
     *currentDest = '-';
     currentDest++;
   }

   *currentDest = '';
   reverse(destBuffer);
   return destBuffer;
}

 

END