ft_itoa_base.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /* ************************************************************************** */
  2. /* */
  3. /* ::: :::::::: */
  4. /* ft_itoa_base.c :+: :+: :+: */
  5. /* +:+ +:+ +:+ */
  6. /* By: mazimi <marvin@42.fr> +#+ +:+ +#+ */
  7. /* +#+#+#+#+#+ +#+ */
  8. /* Created: 2015/12/17 15:24:28 by mazimi #+# #+# */
  9. /* Updated: 2015/12/17 15:56:31 by mazimi ### ########.fr */
  10. /* */
  11. /* ************************************************************************** */
  12. #include "../libft.h"
  13. char *ft_itoa_base(int value, int base)
  14. {
  15. char *str;
  16. int mult;
  17. int len;
  18. int i;
  19. long nbr;
  20. char c;
  21. nbr = value;
  22. mult = 1;
  23. len = 1;
  24. while (nbr / mult >= base || nbr / mult <= -base)
  25. {
  26. mult = mult * base;
  27. len++;
  28. }
  29. len = (nbr < 0) ? len + 1 : len;
  30. str = ft_strnew(len);
  31. str[0] = '-';
  32. i = (nbr < 0) ? 0 : -1;
  33. nbr = (nbr < 0) ? -nbr : nbr;
  34. while (++i < len)
  35. {
  36. c = nbr / mult;
  37. str[i] = (0 <= c && c <= 9) ? c + 48 : c + 55;
  38. nbr = nbr - c * mult;
  39. mult = mult / base;
  40. }
  41. str[i] = '\0';
  42. return (str);
  43. }