Eat a Lemon

because its sour

Convert int to char

Here is the technique for converting an integer to a char array. I once had this as an interview question.
Modulo 10 picks off the last digit of the integer and an integer divide by 10 gets the next character.

223 % 10 = 3
223 / 10 = 22
22 % 10 = 2
22 / 10 = 2
2 % 10 = 2
2 / 10 = 0

Then we get it in reverse.
We either have to calculate the length of the integer ahead of time or reverse the string once it is made.

322
reverse(322)
223

int int_to_char(int integer, char* str, int str_len_max) {
    int len = 0; 
    if(integer < 0) {
        len = 1;
        *str = '-';
    }   
    int test = integer;
    while(test != 0) {
        test = test / 10;
        len++;
    }   
    if( len+1 > str_len_max) {
        return -1;
    }  
    int count = len;
    *(str + count) = '';
    for(count=len; count>0; count--) {
        *(str + count-1) = (char)((integer % 10) + 48);
        integer = integer / 10;
    } 
    return len;
}   
int timestamp(struct tm* ptm, char* timestamp, int len) {
    time_t ltime; /* calendar time */
    ltime=time(NULL); /* get current cal time */
    ptm = gmtime(&ltime);
    char year[5];
    char mon[3];
    char day[3];
    char hour[3];
    char min[3];
    char sec[3];

    int s = int_to_char(ptm->tm_year+1900, year, 5);
    printf("%i: %s\n", s, year);

    if(ptm->tm_mon < 10) {
        mon[0] = '0';
        mon[1] = (char)(ptm->tm_mon + 48);
        mon[2] = '\0';
    } else {
        int_to_char(ptm->tm_mon, mon, 3);
    }
    if(ptm->tm_mday < 10) {
        day[0] = '0';
        day[1] = (char)(ptm->tm_mday + 48);
        day[2] = '\0';
    } else {
       int_to_char(ptm->tm_mday, day, 3);
    }

    if(ptm->tm_hour < 10) {
        hour[0] = '0';
        hour[1] = (char)(ptm->tm_hour + 48);
        hour[2] = '\0';
    } else {
        int_to_char(ptm->tm_hour, hour, 3);
    }

    if(ptm->tm_min < 10) {
        min[0] = '0';
        min[1] = (char)(ptm->tm_min + 48);
        min[2] = '\0';
    } else {
        int_to_char(ptm->tm_min, min, 3);
    }
    if(ptm->tm_sec < 10) {
        sec[0] = '0';
        sec[1] = (char)(ptm->tm_sec + 48);
        sec[2] = '\0';
    } else {
        int_to_char(ptm->tm_sec, sec, 3);
    }

    int bytes = snprintf(timestamp, len, "%s%s%s%s%s%s", year, mon, day, hour, min, sec);
    return bytes;
}
Follow

Get every new post delivered to your Inbox.