the c programming language 2-3

时间:2024-01-05 14:41:38
#include<stdio.h>
#define MAXLINELEN 1000
int power(int base,int n)
{
int i=;
int answer=;
for(i=;i<n;i++)
answer=answer*base;
return answer;
}
/*strlen函数:返回s的长度*/
int strlen(char *s)
{
int i;
i=;
while(s[i]!='\0')
++i;
return i;
}
/*getline函数*/
void getlines(char *s)
{
int i=;
int lim=MAXLINELEN;
int c;
for(i=;i<lim-&&(c=getchar())!='\n'&&c!=EOF;i++)
s[i]=c;
}
/*hexalpha_to_int函数:把单个char转换成int*/
int hexalpha_to_int(int c)
{
if(c>=''&&c<='')
c=c-'';
else if(c>='a'&&c<='z')
c=c-'a'+;
else if(c>='A'&&c<='Z')
c=c-'A'+;
return c;
}
/**/
int htoi(char s[])
{
int len;
int i;
len=strlen(s);
int answer=;
if(s[]==''&&(s[]=='X'||s[]=='x'))
{
for(i=;i<len;i++)
{
answer=hexalpha_to_int(s[i])*power(,len--i)+answer;
}
}
else
{
for(i=;i<len;i++)
{
answer=hexalpha_to_int(s[i])*power(,len--i)+answer;
printf("i:%d\n",i);
printf("hexalpha_to_int(s[i]):%d\n",hexalpha_to_int(s[i]));
printf("power(16,len-1-i):%d\n",power(,len--i));
printf("answer:%d\n",answer);
}
}
return answer;
}
main()
{
char s[MAXLINELEN];
getlines(s);
printf("%d\n",htoi(s));
}