Tuesday 21 February 2017

Implement an itoa function


How do you implement an itoa function?

We can use below logic
1.divide Number by base and store the reminder in a buffer.
2.Change the Number with division result and repeat step 1 till Number become 1
3. reverse the buffer to have final result.


int my_itoa(int number, unsigned short base, char *output, size_t max_len){
        int length = 0;
        if(output == NULL || base > 36){
                return -1;
        }
        for( length=0; length < max_len; length++){
                char digit = number%base;
                if(digit<10){
                        digit += '0';
                }else{
                        digit += ('A'-10);
                }
                output[length] = digit;
                number = number/base;
                if(number==0){
                        break;
                }
        }

        if(length < max_len){
                my_strrev(output); // reverse buffer
        }else{
                return -1;
        }
        return length;
}

complete code


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int my_strrev(char *string){
        if(string == NULL){
                return 0;
        }
        int string_len = strlen(string);
        for(int left=0, right=string_len-1; left < right; left++, right--){
                char temp_ch = string[left];
                string[left] = string[right];
                string[right] = temp_ch;
        }
}

int my_itoa(int number, unsigned short base, char *output, size_t max_len){
        int length = 0;
        if(output == NULL || base > 36){
                return -1;
        }
        for( length=0; length < max_len; length++){
                char digit = number%base;
                if(digit < 10){
                        digit += '0';
                }else{
                        digit += ('A'-10);
                }
                output[length] = digit;
                number = number/base;
                if(number==0){
                        break;
                }
        }

        if(length < max_len){
                my_strrev(output);
        }else{
                return -1;
        }
        return length;
}

int main(int argc, char *argv[]){
        char buffer[256]={0x00};
        int number, base;
        for(int i=0; i < 10; i++){
                number = (rand()%1000)+1;
                base = (rand()%35)+1;
                memset(buffer, 0x00, sizeof(buffer));
                my_itoa(number, base, buffer, 256);
                printf("%d in Base %d =%s\n", number, base, buffer );
        }
        return 0;
}

Compile and Output


rajesh@ideapad:~/Rajesh/Blog/string$ gcc myitoa.c 
rajesh@ideapad:~/Rajesh/Blog/string$ ./a.out 
384 in Base 12 =280
778 in Base 6 =3334
794 in Base 11 =662
387 in Base 3 =112100
650 in Base 32 =KA
363 in Base 13 =21C
691 in Base 5 =10231
764 in Base 22 =1CG
541 in Base 2 =1000011101
173 in Base 17 =A3

No comments:

Post a Comment