khalfella

ansi_c_pg44_ch02_ex03.c

Nov 2nd, 2014
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.80 KB | None | 0 0
  1. /*
  2. * Exercise 2-3.
  3. * Write a function htoi(s), which converts a string of hexadecimal digits
  4. * (including an optional 0x or 0X) into its equivalent integer value.
  5. * The allowable digits are 0 through 9, a through f, and A through F.
  6. */
  7.  
  8.  
  9. #include <stdio.h>
  10.  
  11.  
  12. int
  13. h_to_i(const char* s) {
  14. int i = 0;
  15. int ret = 0;
  16. if (s[i] == '0')
  17. i++;
  18. if (i && (s[i] == 'x' || s[i] == 'X'))
  19. i++;
  20. while (s[i]) {
  21. if (s[i] >= '0' && s[i] <= '9')
  22. ret = ret * 16 + s[i] - '0';
  23. else if (s[i] >= 'a' && s[i] <= 'f')
  24. ret = ret * 16 + s[i] - 'a' + 10;
  25. else if (s[i] >= 'A' && s[i] <= 'F')
  26. ret = ret * 16 + s[i] - 'A' + 10;
  27. else
  28. return -1;
  29. i++;
  30. }
  31.  
  32. return ret;
  33.  
  34. }
  35.  
  36. int
  37. main(int argc, char** argv) {
  38.  
  39. printf("htoi(%s) = %d\n",argv[1], h_to_i(argv[1]));
  40. return 0;
  41.  
  42. }
Advertisement
Add Comment
Please, Sign In to add comment