/03/3-2-ft_atoi_base/ft_atoi_base_withmain.c

https://github.com/fwuensche/42-exam-miner · C · 53 lines · 46 code · 7 blank · 0 comment · 22 complexity · f85e6ece6d959ac2d9b8218f84b5df29 MD5 · raw file

  1. #include <stdio.h>//
  2. #include <stdlib.h>//
  3. int isblank(char c)
  4. {
  5. if (c <= 32)
  6. return (1);
  7. return (0);
  8. }
  9. int isvalid(char c, int base)
  10. {
  11. char digits[17] = "0123456789abcdef";
  12. char digits2[17] = "0123456789ABCDEF";
  13. while (base--)
  14. if (digits[base] == c || digits2[base] == c)
  15. return (1);
  16. return (0);
  17. }
  18. int value_of(char c)
  19. {
  20. if (c >= '0' && c <= '9')
  21. return (c - '0');
  22. else if (c >= 'a' && c <= 'f')
  23. return (c - 'a' + 10);
  24. else if (c >= 'A' && c <= 'F')
  25. return (c - 'A' + 10);
  26. return (0);
  27. }
  28. int ft_atoi_base(const char *str, int str_base)
  29. {
  30. int result;
  31. int sign;
  32. result = 0;
  33. while (isblank(*str))
  34. str++;
  35. sign = (*str == '-') ? -1 : 1;
  36. (*str == '-' || *str == '+') ? ++str : 0;
  37. while (isvalid(*str, str_base))
  38. result = result * str_base + value_of(*str++);
  39. return (result * sign);
  40. }
  41. int main(int ac, char **av)//
  42. {//
  43. if (ac == 3)//
  44. printf("result: %d\n", ft_atoi_base(av[1], atoi(av[2])));//
  45. return (0);//
  46. }//