关于the c programming language 里的一个习题(第二章)——十六进制转十进制
/*
** 编写函数htoi(s),把由十六进制数字组成的字符串(包含可选的前缀0x或0X)
转换为与之等价的整型值。字符串允许包含的数字包括:0~9,a~f以及A~F。
*/
#define YES 1
#define NO 0
/* htoi:convert hexadecimal string s to integer*/
int htoi(char s[]){
int hexdigit, i, ishex, result;
i = 0;
if(s[i] =='0'){ /*skip optional 0x or 0X*/
++i;
if(s[i] == 'x' || s[i] == 'X'){
++i;
}
}
result = 0; /*integer value to be returned*/
ishex = YES; /*asume valid hexadecimal digit*/
for(; ishex == YES; ++i){
if(s[i] >= '0' && s[i] <= '9'){
hexdigit = s[i] - '0';
}
else if(s[i] >= 'a' && s[i] <= 'f'){
hexdigit = s[i] - 'a' +10;
}
else if(s[i] >= 'A' && s[i] <= 'F'){
hexdigit = s[i] - 'A' +10;
}
else{
ishex = NO; /*not a valid hexadecimal digit*/
}
if(ishex == YES){
result = 16 * result + hexdigit;
}
}
return result;
}
main(){
char s[] = "0x5A";
printf("%d\n",htoi(s));
}
//----------------------------------------------------------------------
其中用了这么一句:
result = 16 * result + hexdigit;
请问这是怎么推导出来的?