#
include<stdio.h>
#
include<
string.h>
int htoi(
char s[]);
int main(){
char s[
20];
printf(
"Please input a hexadecimal number\n");
char c;
int i=
0;
while((c=getchar())!=EOF&&(c!=
' ')&&(c!=
'\n')){
s[i++]=c;
}
s[i]=
' ';
printf(
"%d\n",htoi(s));
return
0;
}
int htoi(
char s[]){
int start=
0,
end;
int inte=
0;
if(s[
0]==
'0'&&(s[
1]==
'x'||s[
1]==
'X')){
start=
2;
}
int j=
0;
while(s[j++]!=
' '){
}
end=j-
2;
for(
int i=
1;
end>=start;i=i*
16){
if(s[
end]>=
'0'&&s[
end]<=
'9'){
inte=inte+(s[
end]-
'0')*i;
}
else if(s[
end]>=
'a'&&s[
end]<=
'f'){
inte=inte+(s[
end]-
'a'+
10)*i;
}
else if(s[
end]>=
'A'&&s[
end]<=
'F'){
inte=inte+(s[
end]-
'A'+
10)*i;
}
end--;
}
return inte;
}
执行结果如下图所示:
转载请注明原文地址: https://www.6miu.com/read-34559.html