The C standard library does not have an itoa function, but you can easily implement it by yourself. The itoa Function converts a integer value to its string representation which is char* in C. It supports different base system from 2 (Binary) to 36.
Here is a simple implementation of itoa:
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 | #include <string.h> #include <stdlib.h> char* itoa(int value, char* result, int base) { // check that the base is valid if (base < 2 || base > 36) { *result = '\0'; return result; } char* ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "0123456789abcdefghijklmnopqrstuvwxyz"[abs(tmp_value % base)]; } while (value); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while(ptr1 < ptr) { tmp_char = *ptr; *ptr--= *ptr1; *ptr1++ = tmp_char; } return result; } |
#include <string.h> #include <stdlib.h> char* itoa(int value, char* result, int base) { // check that the base is valid if (base < 2 || base > 36) { *result = '\0'; return result; } char* ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "0123456789abcdefghijklmnopqrstuvwxyz"[abs(tmp_value % base)]; } while (value); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while(ptr1 < ptr) { tmp_char = *ptr; *ptr--= *ptr1; *ptr1++ = tmp_char; } return result; }
This version of itoa takes three arguments:
- value is the integer to convert
- result is a pointer to the buffer where the string representation will be stored
- base is the base to use for the conversion, which can be between 2 and 36 inclusive (allowing for binary, decimal, hexadecimal, and every base in between)
Note that this function operates in-place (it directly modifies the result buffer), and does not allocate any memory. Make sure you pass a buffer that's big enough to hold the string representation of the integer. For base 2, you need 33 chars (32 bits + sign), for base 10, you need 12 chars (10 digits + sign + '\0') and so on.
The implementation itself is straightforward: it performs the base conversion by repeatedly dividing the value by the base and picking the remainder, until the value is zero. The remainders are then turned into digits (0-9a-z) and stored in the buffer. If the original number was negative, a minus sign is added. Finally, since the number was built backwards, the function reverses it before returning.
--EOF (The Ultimate Computing & Technology Blog) --
loading...
Last Post: C Implementation of the iota Function (Increasing Sequence)
Next Post: Two Year Anniversary of Joining Microsoft Research Cambridge as a Senior Software Engineer