char * itoa ( int value, char * str, int base );
The content we insert into the buffer parameter needs to be sufficiently spacious to accommodate the resulting output. Radix values can be either in OCTAL (0-7), DECIMAL (0-9), or HEX (0-9, a-f) formats. In cases where the radix is set to DECIMAL, the itoa function generates ```
char itoa ( int value, char str, int base );
(void) sprintf(buffer, "%d", n);
Here, buffer returns character string.
When the base is OCTAL, the itoa() function converts the integer 'n' into an unsigned octal value.
When the base is hexadecimal (HEX), the itoa() function converts the integer 'n' into an unsigned hexadecimal value.
The hexadecimal number will contain lowercase letters.
### Return value -
The function will provide the string pointer as output. In case of an invalid radix argument, the function will return a NULL value.
A standard-compliant alternative -
- sprintf(str,"%d",value) - For conversion to decimal base.
- sprintf(str,"%x",value) - For conversion to hexadecimal base.
- sprintf(str,"%o",value) - For conversion to octal base.
Algorithm:
Step 1: Take a number as argument
Step 2: Create an empty string buffer to store result
Step 3: Use sprintf to convert number to string
Step 4: End
CODE -
include <stdio.h>
include <math.h>
include <stdlib.h>
char itoa(int num, char buffer, int base)
{
int current = 0;
if (num == 0) {
buffer[current++] = '0';
buffer[current] = '\0';
return buffer;
}
int num_digits = 0;
if (num < 0) {
if (base == 10) {
num_digits ++;
buffer[current] = '-';
current ++;
num *= -1;
}
else
return NULL;
}
num_digits += (int)floor(log(num) / log(base)) + 1;
while (current < num_digits)
{
int baseval = (int) pow(base, numdigits-1-current);
int numval = num / baseval;
char value = num_val + '0';
buffer[current] = value;
current ++;
num -= baseval * numval;
}
buffer[current] = '\0';
return buffer;
}
int main
{
int a = 123456;
char buffer[256];
if (itoa(a, buffer, 10) != NULL) {
printf("Input = %d, base = %d, Buffer = %s\n", a, 10, buffer);
}
int b = -2310;
if (itoa(b, buffer, 10) != NULL) {
printf("Input = %d, base = %d, Buffer = %s\n", b, 10, buffer);
}
int c = 10;
if (itoa(c, buffer, 2) != NULL) {
printf("Input = %d, base = %d, Buffer = %s\n", c, 2, buffer);
}
return 0;
}
Output
Input = 123456, base = 10, Buffer = 123456
Input = -2310, base = 10, Buffer = -2310
Input = 10, base = 2, Buffer = 1010
#### Note: But we have to keep in mind that while we are compiling with gcc, we have to use the '-lm' flag to include the math library.
gcc -o test.out test.c -lm