ft_itoa_base.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* ************************************************************************** */
  2. /* */
  3. /* ::: :::::::: */
  4. /* ft_itoa_base.c :+: :+: :+: */
  5. /* +:+ +:+ +:+ */
  6. /* By: bchanot <bchanot@student.42.fr> +#+ +:+ +#+ */
  7. /* +#+#+#+#+#+ +#+ */
  8. /* Created: 2018/10/12 03:26:09 by bchanot #+# #+# */
  9. /* Updated: 2018/10/29 11:49:37 by bchanot ### ########.fr */
  10. /* */
  11. /* ************************************************************************** */
  12. #include "libft.h"
  13. static int ft_ulen(t_uint64 value, t_uint8 base)
  14. {
  15. int i;
  16. i = 0;
  17. while (value / base)
  18. i++;
  19. return (i);
  20. }
  21. char *ft_utoa_base(t_uint64 value, t_uint8 base)
  22. {
  23. const char hex[16] = "0123456789abcdef";
  24. char *s;
  25. int i;
  26. i = ft_ulen(value, base);
  27. s = ft_strnew(i);
  28. while (value / base)
  29. {
  30. s[i] = hex[value % base];
  31. value /= base;
  32. i--;
  33. }
  34. return (s);
  35. }
  36. static int ft_len(t_int64 value, t_uint8 base)
  37. {
  38. int i;
  39. i = 0;
  40. while (value / base)
  41. i++;
  42. return (i);
  43. }
  44. char *ft_itoa_base(t_int64 value, t_uint8 base)
  45. {
  46. const char hex[16] = "0123456789abcdef";
  47. char *s;
  48. int i;
  49. int neg;
  50. neg = value < 0 && base == 10 ? 1 : 0;
  51. value = value < 0 ? -value : value;
  52. i = ft_len(value, base) + neg;
  53. s = ft_strnew(i);
  54. while (value / base)
  55. {
  56. s[i] = hex[value % base];
  57. value /= base;
  58. i--;
  59. }
  60. if (neg)
  61. s[i] = '-';
  62. return (s);
  63. }