Posted By

zava on 08/05/10


Tagged

convert atoi


Versions (?)

convert ascii to integer without using atoi()


 / Published in: C
 

  1. int _asc2int(const char* s)
  2. {
  3. int i = 0;
  4. // return 0 on any other character
  5. while (*s != 0)
  6. {
  7. if (*s >= '0' && *s <= '9')
  8. {
  9. i = i * 10 + (*s - '0');
  10. s++;
  11. }
  12. else return 0;
  13. }
  14. return i;
  15.  
  16. }
  17. int asc2int(const char* s)
  18. {
  19. // leading '+' and '-' allowed
  20. int sign = 1;
  21. if (*s == '+') s++;
  22. if (*s == '-')
  23. {
  24. sign = -1;
  25. s++;
  26. }
  27. return _asc2int(s) * sign;
  28. }
  29.  
  30. int main()
  31. {
  32. char s[] = "-975310";
  33. printf("'%s' => %dn", s, asc2int(s));
  34. return 0;
  35. }

Report this snippet  

You need to login to post a comment.