字符串转换成十进制整数.c 769 B

123456789101112131415161718192021222324252627282930313233343536
  1. #include <stdio.h>
  2. #include <ctype.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5. int main() {
  6. char str[100];
  7. fgets(str, 100, stdin);
  8. // Remove newline character
  9. str[strcspn(str, "\n")] = '\0';
  10. int is_negative = 0;
  11. int hex_found = 0;
  12. int i;
  13. unsigned long long decimal = 0;
  14. for (i = 0; str[i] != '#'; i++) {
  15. if (str[i] == '-') {
  16. is_negative = 1;
  17. } else if (isxdigit(str[i])) {
  18. hex_found = 1;
  19. char hex_char = toupper(str[i]);
  20. int hex_value = isdigit(hex_char) ? hex_char - '0' : hex_char - 'A' + 10;
  21. decimal = decimal * 16 + hex_value;
  22. }
  23. }
  24. if (is_negative) {
  25. decimal = -decimal;
  26. }
  27. printf("%lld\n", decimal);
  28. return 0;
  29. }