Implement itoa() function in C
Write an efficient function to implement itoa() function in C. The standard itoa() function converts input number to its corresponding C-string using the specified base.
Prototype:
The prototype of the itoa() is:
char* itoa(int value, char* buffer, int base);
Parameters:
value – Value to be converted to a string.
buffer – Array to store the resulting null-terminated string.
base – Numerical base used to represent the value as a string, between 2 and 36.
Return Value:
A pointer to the resulting null-terminated string, same as parameter buffer.
C
|
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
#include <stdio.h> #include <stdlib.h> // Function to swap two numbers void swap(char *x, char *y) { char t = *x; *x = *y; *y = t; } // Function to reverse `buffer[i…j]` char* reverse(char *buffer, int i, int j) { while (i < j) { swap(&buffer[i++], &buffer[j--]); } return buffer; } // Iterative function to implement `itoa()` function in C char* itoa(int value, char* buffer, int base) { // invalid input if (base < 2 || base > 32) { return buffer; } // consider the absolute value of the number int n = abs(value); int i = 0; while (n) { int r = n % base; if (r >= 10) { buffer[i++] = 65 + (r - 10); } else { buffer[i++] = 48 + r; } n = n / base; } // if the number is 0 if (i == 0) { buffer[i++] = '0'; } // If the base is 10 and the value is negative, the resulting string // is preceded with a minus sign (-) // With any other base, value is always considered unsigned if (value < 0 && base == 10) { buffer[i++] = '-'; } buffer[i] = '\0'; // null terminate string // reverse the string and return it return reverse(buffer, 0, i - 1); } // Implement itoa function in C int main(void) { char buffer[33]; int value[] = { 11184810, -25, 64, 127 }; int base[] = { 16, 10, 8, 2 }; for (int i = 0; i < 4; i++) { printf("itoa(%d, buffer, %d) = %s\n", value[i], base[i], itoa(value[i], buffer, base[i])); } return 0; } |
Output:
itoa(11184810, buffer, 16) = AAAAAA
itoa(-25, buffer, 10) = -25
itoa(64, buffer, 8) = 100
itoa(127, buffer, 2) = 1111111
That’s all about itoa() implementation in C.
Related Post:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)