From 6225bb83c6f5f569f2994bd2be1915f3aa66c7bf Mon Sep 17 00:00:00 2001 From: Aaron Ball Date: Mon, 23 Feb 2015 12:14:26 -0700 Subject: Wrote itoc common function This function converts an integer to its char array equivelant. --- src/common.c | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/common.h | 2 ++ 2 files changed, 62 insertions(+) diff --git a/src/common.c b/src/common.c index ad40025..7cbdc3e 100644 --- a/src/common.c +++ b/src/common.c @@ -32,3 +32,63 @@ void get_user_editor(char* editor) { strcpy(editor, "vi"); } } + + +/** + * Converts an integer to its equivelant char array + * + * @param i The integer to be converted + * @param out Char array pointer to the output variable. Must be large enough + * to hold the output or unpredictable behavior may result. + * + * @return int The char count, not including the terminating null byte char + */ +int itoc(int num, char* out) { + int count = 0; + + int tmp_num = num; + // Get a char count. This is necessary becasue the numbers come out + // backwards. We need to start from the end and work back. + while(tmp_num > 0) { + //int n = tmp_num%10; + tmp_num /= 10; + count++; + } + + int out_count = count; + + // Set the last char as a null byte + out[count] = '\0'; + count--; + + while(count >= 0) { + int n = num%10; + + if(n == 0) { + out[count] = '0'; + } else if(n == 1) { + out[count] = '1'; + } else if(n == 2) { + out[count] = '2'; + } else if(n == 3) { + out[count] = '3'; + } else if(n == 4) { + out[count] = '4'; + } else if(n == 5) { + out[count] = '5'; + } else if(n == 6) { + out[count] = '6'; + } else if(n == 7) { + out[count] = '7'; + } else if(n == 8) { + out[count] = '8'; + } else if(n == 9) { + out[count] = '9'; + } + + num /= 10; + count--; + } + + return out_count; +} diff --git a/src/common.h b/src/common.h index b11fd8c..89b9026 100644 --- a/src/common.h +++ b/src/common.h @@ -23,4 +23,6 @@ void get_user_editor(char*); +int itoc(int, char*); + #endif -- cgit v1.2.3