aboutsummaryrefslogtreecommitdiff
path: root/src/libc/string.c
blob: 93a9e6366550e6e4d0dc014ef395f0d0aeffb74b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include "string.h"
#include "math.h"

void itoa(int i, char *a){
    // Check if lower than 0
    char neg=0;
    if(i<0){
        neg=1;
        i=-i;
        a[0]='-';
    }

    // Count number of digits
    int len=1;
    while(i/pow(10,len)>=1)
    {
        len++;
    }

    // Build string
    int max_pow=len-1;
    for(int j=0;j<=max_pow;j++){
        int cur_pow=pow(10,max_pow-j);
        char digit=i/cur_pow;
        a[j+neg]='0'+digit;
        i=i-digit*cur_pow; // Remove first digits (most significant)
    }
    a[len+neg]='\0';
}