Skip to content

Instantly share code, notes, and snippets.

@hamza-cskn
Last active February 12, 2023 21:25
Show Gist options
  • Save hamza-cskn/1661967ca32e24689c8fa259b742411a to your computer and use it in GitHub Desktop.
Save hamza-cskn/1661967ca32e24689c8fa259b742411a to your computer and use it in GitHub Desktop.
converts integers to string.
int power(int n, int pow) {
int res = n;
if (pow == 0) return 1;
while (--pow > 0) res *= n;
return res;
}
// increases 'pow' until find the smallest power of 10
// which is bigger than the number. and its gives the digit count.
int count_digits(int nbr) {
if (nbr == 0) return 1; //zero is smaller than all powers of ten.
if (nbr < 0) nbr = -nbr; //get absolute value
int pow = 0;
while (nbr >= power(10, pow++));
return pow - 1;
}
//if you divide 12345(nbr) by 100(power(10, digit - 1)), it would be equal to 123(nbr / power(10, digit - 1)).
//if you continue, and you divide it by 10, its remainder will be 3((nbr / power(10, digit - 1)) % 10).
int get_digit(int nbr, int digit) {
if (nbr < 0) nbr = -nbr;
return (nbr / power(10, digit - 1)) % 10;
}
char *ft_itoa(int nbr) {
int negativity = nbr < 0; //negative numbers are '-' signed, so you have to care it.
int digit_amount = count_digits(nbr);
int length = digit_amount + negativity;
char *result = malloc( (length));
if (negativity) result[0] = '-';
int i = negativity; //if positive, start at 0. index, otherwise start at 1. index because we have '-' sign.
while (i < length) {
result[(length - 1) - i + negativity] = get_digit(nbr, i + 1 - negativity) + 48;
i++;
}
return result;
}
int main() {
printf("numb: %s", ft_itoa(-12948));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment