fork download
  1. #include <stdio.h>
  2. #include <memory.h>
  3.  
  4. #define BEGIN_HEX 0 /*Íà÷àëî çàïèñè 16-ðè÷íîãî ÷èñëà*/
  5. #define HEX 1 /*Òî÷íî èçâåñòíî, ÷òî ýòî 16-ðè÷íîå ÷èñëî*/
  6. #define NUMBER 2 /* çíà÷àùåé ÷àñòè 16-ðè÷íîãî ÷èñëà*/
  7. #define STRING 3 /*Åñëè ïåðåäàíî íå ÷èñëî, à ëþáàÿ ñòðîêà*/
  8. #define START_PARSING 4
  9.  
  10. int htoi(char s[]);
  11.  
  12. int main(void){
  13. int i;
  14.  
  15. i = htoi("0x9");
  16. printf("%d\n", i);
  17. return 0;
  18. }
  19.  
  20. int htoi(char s[]){
  21. int res;
  22. int i;
  23. int state;
  24.  
  25. i = res = 0;
  26. state = START_PARSING;
  27. while(s[i] != '\0'){
  28. if(s[i] == '0')
  29. if(state == START_PARSING)
  30. {state = BEGIN_HEX; printf("state = BEGIN_HEX\n");}
  31. else
  32. {state == STRING; printf("state = STRING1\n"); }
  33. else if(s[i] == 'x')
  34. if(state == BEGIN_HEX)
  35. {state = HEX; printf("state = HEX\n");}
  36. else
  37. {state = STRING; printf("state = STRING2\n");}
  38. else if(state == HEX){ /*Íà÷èíàåì ðàçáîð 16-ðè÷íîãî ÷èñëà*/
  39. if((s[i] >= '0' && s[i] <= '9' ) || (s[i] >= 'A' && s[i] <= 'F')){
  40. res = res*16 + (s[i] - '0');
  41. printf("s[i] = %d\n", s[i]);
  42. printf("s[i] - 0 = %d\n", s[i] - '0');
  43. }else{
  44. state = STRING;
  45. printf("state = STRING");
  46. }
  47. }
  48. i++;
  49. }
  50.  
  51. return res;
  52. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
state = BEGIN_HEX
state = HEX
s[i] = 57
s[i] - 0 = 9
9