ft_itob.c 1.5 KB

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