Hello everyone, I'm working on a small assignment where I am supposed to write the code for the itoa function char* itoa(int Value, int Base);
without using any built-in functions, and where the returned value is allocated on behalf of the caller. Value being the integer to convert, and base being octal, decimal, or hex.
I found this rather simple implementation and I was hoping we could discuss it here to see if the changes I'm making are appropriate/accurate and etc.
char* itoa(int val, int base){
static char buf[32] = {0};
int i = 30;
for(; val && i ; --i, val /= base)
buf[i] = "0123456789abcdef"[val % base];
return &buf[i+1];
}
Here's my current, pseudo-codey implementation:
char* itoa(int val, int base){
static char buf[36] = {0};
buf = (char *) malloc(//...);
if (val == 0)
return &buf=0;
//since base can only be octal, decimal or hex
if (base != 8 || base != 10 || base != 16)
printf("Not a valid base.");
for(int i=30; val && i; --i)
{
val /= base;
buf[i] = "0123456789abcdef"[val % base];
}
if(value < 0 && base == 10)
//make the output negative
return &buf[i+1];
}
Thanks in advance! :)