diff --git a/lib/conv.c b/lib/conv.c index 8c9284c..731ea6a 100644 --- a/lib/conv.c +++ b/lib/conv.c @@ -1,12 +1,13 @@ #include "conv.h" void int_to_str(int i, char* buf) { - bool use_sign = false; + uint num = (uint)i; // convert to uint + uint len = ulong_len(num); // number of digits - if( i < 0 ) { - i = (ulong)(i * (-1)) - use_sign = true; - } + &buf[len] = '\0'; // add a "end-of-string" at the end + + int j; + for(j = 0; j < len; j++) // iterate over each digit and assign it to the buffer + &buf[j] = (char)(ndigit(num, len-1-j) + ASCII_OFFSET); // apply the ascii offset so that i becomes a char - uint len = ulong_len(i); } diff --git a/lib/conv.h b/lib/conv.h index 3e4e383..776644b 100644 --- a/lib/conv.h +++ b/lib/conv.h @@ -1,3 +1,5 @@ #include "types.h" +#define ASCII_OFFSET 0x30 + void int_to_str(int i, char* buf); diff --git a/lib/util.c b/lib/util.c index f534869..4690128 100644 --- a/lib/util.c +++ b/lib/util.c @@ -1,10 +1,14 @@ #include "util.h" -uint ulong_len(ulong i) { +uint ulong_len(ulong n) { // get the digit length of a number int len = 0; - while (i != 0) { - i = i / 10; + while (n != 0) { + n = n / 10; ++len; } return len; } + +uint ndigit(ulong n, uint i) { // OBS: index order is reversed + return (n/(10**i)) % 10 +} diff --git a/lib/util.h b/lib/util.h index 6c4e531..2cebf96 100644 --- a/lib/util.h +++ b/lib/util.h @@ -1,3 +1,4 @@ #include "types.h" uint ulong_len(ulong n); +uint ndigit(ulong n, uint i);