ft_htoa.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /* ************************************************************************** */
  2. /* */
  3. /* ::: :::::::: */
  4. /* ft_htoa.c :+: :+: :+: */
  5. /* +:+ +:+ +:+ */
  6. /* By: bchanot <bchanot@students.42.fr> +#+ +:+ +#+ */
  7. /* +#+#+#+#+#+ +#+ */
  8. /* Created: 2016/02/11 19:54:05 by bchanot #+# #+# */
  9. /* Updated: 2016/05/15 21:41:51 by bchanot ### ########.fr */
  10. /* */
  11. /* ************************************************************************** */
  12. #include "libft.h"
  13. #include <stdlib.h>
  14. static int valuehex(int x)
  15. {
  16. if (x >= 0 && x <= 9)
  17. return (48 + x);
  18. else if (x >= 10 && x <= 15)
  19. {
  20. x = x - 10;
  21. return (97 + x);
  22. }
  23. return (0);
  24. }
  25. char *ft_htoa(long long unsigned int nb)
  26. {
  27. long long unsigned int x;
  28. char *str;
  29. int cpt;
  30. x = nb;
  31. cpt = 0;
  32. while (x > 16)
  33. {
  34. x /= 16;
  35. cpt++;
  36. }
  37. str = (char *)malloc(sizeof(char *) * cpt + 1);
  38. if (str)
  39. {
  40. str[cpt + 1] = '\0';
  41. while (cpt >= 0)
  42. {
  43. x = nb % 16;
  44. str[cpt] = valuehex(x);
  45. nb /= 16;
  46. cpt--;
  47. }
  48. }
  49. return (str);
  50. }