c語言將16進位制轉換成10進位制
阿新 • • 發佈:2018-12-13
前言
要轉換的字串中包含可選的字首0x或者0X,
程式碼
/* * Created by sutaoyu on 2018/10/2 * */ #include<stdio.h> #include<ctype.h> #define YES 1 #define NO 0 int htoi(char s[]) { int hexdigit, i, inhex, n; i = 0; if (s[i] == '0') { ++i; if (s[i] == 'x' || s[i] == 'X') { ++i; } } n = 0; inhex = YES; for ( ; inhex == YES; ++i) { if (s[i] >= '0' && s[i] <= '9') { hexdigit = s[i] - '0'; } else if (tolower(s[i]) >= 'a' && tolower(s[i]) <= 'z') { hexdigit = s[i] - 'a' + 10; } else { inhex = NO; } if (inhex == YES) { n = 16 * n + hexdigit; } } return n; } int main() { char s[100]; scanf("%s", s); printf("char is %s\n", s); printf("integer is %d\n", htoi(s)); return 0; }