十六进制转十进制 谭浩强教材课后习题
#include<stdio.h> size_t HextoDec(char s[]) { size_t i, n; n = 0; for (i = 0; s[i] != '\0'; i++) { if (s[i] >= '0'&& s[i] <= '9') n = n * 16 + s[i] - '0'; if (s[i] >= 'a' && s[i] <= 'f') n = n * 16 + s[i] - 'a' + 10; if (s[i] >= 'A' && s[i] <= 'F') n = n * 16 + s[i] - 'A' + 10; } return n; } int main() { size_t result = 0; char hex[9] = {0}; printf("input a HEX number:"); scanf("%s", hex); result = HextoDec(hex); printf("0x%s = %u\n", hex, result); return 0; }
转自博客https://blog.csdn.net/gjggj/article/details/92415602
略微注释
#include<stdio.h> int HextoDec(char s[]) { int i,n; n=0;//n为最后结果 for (i=0;s[i]!='\0';i++)//设置循环来读取数组中的数,每一次循环最高位的数的位权都会加1(最高位为第一位) { if (s[i]>='0'&&s[i]<='9') n=n*16+s[i]-'0';//减去0字符的ascii码来达到同步 if (s[i] >= 'a' && s[i]<='f')//大小写一致 n=n*16+s[i]-'a'+10; if (s[i]>='A'&&s[i]<='F') n=n*16+s[i]-'A'+10; } return n; } int main() { int result=0; char hex[9]={0}; printf("输入一个十六进制数:"); scanf("%s", hex); result=HextoDec(hex); printf("0x%s = %u\n",hex,result); return 0; }
人生如逆旅,我亦是行人