Skip to content

Instantly share code, notes, and snippets.

@abdorah
Last active November 16, 2023 08:31
Show Gist options
  • Save abdorah/10fe4d184d3cea3d352fa90661d86abc to your computer and use it in GitHub Desktop.
Save abdorah/10fe4d184d3cea3d352fa90661d86abc to your computer and use it in GitHub Desktop.
This gist represents my implementation of the itoa function in c.

int to string itoa() function in c

Motivation: I tried once to use the itoa() function in one of my c programs, but it seems that it doesn't work... so I decided to make my own implementation to cast an int into string.

This code was based on various resources, still it is easy to understand and to use. For example:

int main() 
{ 
 char str[100]; 
 printf("the result of itoa: %s", itoa(3267,str,10));
 return 0; 
} 
#include <stdio.h>
#include <stdlib.h>
typedef enum{false, true} bool;
void swap(char *a, char *b)
{
if(!a || !b)
return;
char temp = *(a);
*(a) = *(b);
*(b) = temp;
}
void reverse(char *str, int length)
{
int start = 0;
int end = length -1;
while (start < end)
{
swap((str+start), (str+end));
start++;
end--;
}
}
char* itoa(int num, char* str, int base)
{
int i = 0;
bool isNegative = false;
if (num == 0)
{
str[i++] = '0';
str[i] = '\0';
return str;
}
if (num < 0 && base == 10)
{
isNegative = true;
num = -num;
}
while (num != 0)
{
int rem = num % base;
str[i++] = (rem > 9)? (rem-10) + 'a' : rem + '0';
num = num/base;
}
if (isNegative == true)
str[i++] = '-';
str[i] = '\0';
reverse(str, i);
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment