练习2-3 编写函数 htoi(s),把由十六进制数字组成的字符串(包含可选的前缀0x或0X)转换为与之等价的整型值。字符串中允许包含的数字包括:0~9、a~f以及A~F。

xiaoxiao2021-02-28  144

#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

最新回复(0)