ft_itoa_base_depth.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* ************************************************************************** */
  2. /* */
  3. /* ::: :::::::: */
  4. /* ft_itoa_base.c :+: :+: :+: */
  5. /* +:+ +:+ +:+ */
  6. /* By: bchanot <bchanot@student.42.fr> +#+ +:+ +#+ */
  7. /* +#+#+#+#+#+ +#+ */
  8. /* Created: 2017/02/01 15:26:43 by bchanot #+# #+# */
  9. /* Updated: 2018/10/13 20:32:40 by bchanot ### ########.fr */
  10. /* */
  11. /* ************************************************************************** */
  12. #include "libft.h"
  13. static void ft_itoa_loop(t_int64 nb, char **s, t_uint8 base, size_t depth)
  14. {
  15. const char *hex = "0123456789abcdef";
  16. t_uint64 index;
  17. index = nb % base;
  18. if (nb / base > 0)
  19. ft_itoa_loop(nb / base, s, base, (depth - 1));
  20. (*s)[depth] = hex[index];
  21. }
  22. char *ft_itoa_base_depth(t_int64 nb, t_uint8 base, size_t depth)
  23. {
  24. char *s;
  25. size_t i;
  26. if (!(s = ft_strnew(depth + 1)))
  27. return (NULL);
  28. i = 0;
  29. while (i <= depth)
  30. s[i++] = '0';
  31. ft_itoa_loop(nb, &s, base, depth);
  32. return (s);
  33. }
  34. static void ft_utoa_loop(t_uint64 nb, char **s, t_uint8 base, size_t depth)
  35. {
  36. const char *hex = "0123456789abcdef";
  37. t_uint64 index;
  38. index = nb % base;
  39. if (nb / base > 0)
  40. ft_utoa_loop(nb / base, s, base, (depth - 1));
  41. (*s)[depth] = hex[index];
  42. }
  43. char *ft_utoa_base_depth(t_uint64 nb, t_uint8 base, size_t depth)
  44. {
  45. char *s;
  46. size_t i;
  47. if (!(s = ft_strnew(depth + 1)))
  48. return (NULL);
  49. i = 0;
  50. while (i <= depth)
  51. s[i++] = '0';
  52. ft_utoa_loop(nb, &s, base, depth);
  53. return (s);
  54. }