summaryrefslogtreecommitdiff
path: root/src/common.c
blob: 311e259aa5d8c626999e31480430870062f6f292 (plain)
    1 /**
    2  * Copyright (C) 2015 Aaron Ball <nullspoon@iohq.net>
    3  * 
    4  * This program is free software: you can redistribute it and/or modify
    5  * it under the terms of the GNU General Public License as published by
    6  * the Free Software Foundation, either version 3 of the License, or
    7  * (at your option) any later version.
    8  * 
    9  * This program is distributed in the hope that it will be useful,
   10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
   11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   12  * GNU General Public License for more details.
   13  * 
   14  * You should have received a copy of the GNU General Public License
   15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
   16  */
   17 #include "common.h"
   18 
   19 /**
   20  * The complimentary function to the posix atoi. It turns an integer into a
   21  * string.
   22  *
   23  * @param i Integer to be converted to string
   24  * @param out Output char array. Be sure it has enough room for the output
   25  *            string.
   26  *
   27  * @return int The character count of the output char array
   28  */
   29 int itoa(int i, char* out) {
   30   char buf[256];
   31   int n = 0;
   32 
   33   // To keep track of where we are in the array
   34   while(i > 9) {
   35     // This is some crazy simple math here
   36     buf[n] = (i%10) + 48;
   37     // It's an int, so the last number will be stripped
   38     i = i/10;
   39     n++;
   40   }
   41   // Have to do this one more time to ensure we get the last number on
   42   // zero-ended ints
   43   buf[n] = (i%10) + 48;
   44   // Account for the last char
   45   n++;
   46   // Annnd the null byte
   47   buf[n] = '\0';
   48 
   49 
   50   // Now we have to reverse the digit order, because it was read in right to
   51   // left, not left to right (which populating an array requires ltr).
   52   int reversen = n - 1;
   53   int cursor = 0;
   54   // Reverse the order
   55   while(buf[cursor] != '\0') {
   56     out[reversen] = buf[cursor];
   57     cursor++;
   58     reversen--;
   59   }
   60   out[n] = '\0';
   61   
   62   return n;
   63 }

Generated by cgit