R
rajash
Thanks to everyone for interesting discussions. To make the group
happy, my next listing has int main and headers declared!!
Here is my solution to Exercise 2.3.
// write htoi, hex to int
#include<stdio.h>
int main(int c, char **v)
{
int x=-1, htoi();
if(c>1)
x=htoi(v[1]);
if(x>=0)
printf("%d\n", x);
else
printf("Unspecified error.\n");
}
int htoi(char *s)
{
char *t=s;
int x=0, y=1;
if(*s=='0' && (s[1]=='x' || s[1]=='X'))
t+=2;
s+=strlen(s);
while(t<=--s) {
if('0' <= *s && *s <= '9')
x+=y*(*s - '0');
else if('a' <= *s && *s <= 'f')
x+=y*(*s - 'a' + 10);
else if('A' <= *s && *s <= 'F')
x+=y*(10 + *s - 'A');
else
return -1; /* invalid input! */
y<<=4;
}
return x;
}
happy, my next listing has int main and headers declared!!
Here is my solution to Exercise 2.3.
// write htoi, hex to int
#include<stdio.h>
int main(int c, char **v)
{
int x=-1, htoi();
if(c>1)
x=htoi(v[1]);
if(x>=0)
printf("%d\n", x);
else
printf("Unspecified error.\n");
}
int htoi(char *s)
{
char *t=s;
int x=0, y=1;
if(*s=='0' && (s[1]=='x' || s[1]=='X'))
t+=2;
s+=strlen(s);
while(t<=--s) {
if('0' <= *s && *s <= '9')
x+=y*(*s - '0');
else if('a' <= *s && *s <= 'f')
x+=y*(*s - 'a' + 10);
else if('A' <= *s && *s <= 'F')
x+=y*(10 + *s - 'A');
else
return -1; /* invalid input! */
y<<=4;
}
return x;
}