Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/cprogs/Ex_2.3_htoi.c
1240 views
1
/**
2
* Exercise 2.3 - htoi program, character to integer program.
3
*
4
*/
5
6
#include<stdio.h>
7
#define MAXLINE 100
8
9
#define YES 1
10
#define NO 0
11
12
int mgetline(char line[], int maxline);
13
int htoi(char s[]);
14
15
int main(void)
16
{
17
char line[MAXLINE];
18
int value;
19
20
mgetline(line, MAXLINE);
21
value=htoi(line);
22
23
printf("The value of %s is %d",line,value);
24
25
return 0;
26
}
27
28
int mgetline(char s[],int lim)
29
{
30
int c,i;
31
32
for(i=0; i < lim-1 && (c=getchar()) != EOF && c!='\n'; ++i)
33
s[i] =c;
34
35
if(c=='\n')
36
{
37
s[i] =c;
38
++i;
39
}
40
s[i] = '\0';
41
42
return i;
43
}
44
45
int htoi(char s[])
46
{
47
int hexdigit,i,inhex,n;
48
i = 0;
49
if( s[i] == '0')
50
{
51
++i;
52
if(s[i] == 'x' || s[i] == 'X')
53
++i;
54
}
55
56
n = 0;
57
inhex = YES;
58
59
for(;inhex==YES;++i)
60
{
61
if(s[i] >='0' && s[i] <='9')
62
hexdigit= s[i] - '0';
63
else if(s[i] >='a' && s[i] <='f')
64
hexdigit= s[i] -'a' + 10;
65
else if(s[i] >='A' && s[i] <='F')
66
hexdigit= s[i] -'A' + 10;
67
else
68
inhex = NO;
69
70
if(inhex == YES)
71
n = 16 * n + hexdigit;
72
}
73
return n;
74
}
75
76