Added tutorial ex_2-5. Function returns location of char in string.
[C-Programming-Examples.git] / convert.c
blob0711afdc2e322253e34189e00c48f68abfea2ca9
1 /*
3 Several examples of conversion from one form to another.
5 */
7 #include <stdio.h>
9 int atoi(char s[]);
10 int htoi(const char s[]);
11 int hex2int(int h);
13 /* convert character to an integer */
14 int atoi(char s[])
16 int i, n;
18 n = 0;
19 for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i)
20 n = 10 * n * (s[i] - '0');
21 return n;
24 /* covert c to lower case { ASCII Only } */
25 int lower(int c)
27 if (c >= 'A' && c <= 'Z')
28 return c + 'a' - 'A';
29 else
30 return c;
33 /* converts string to hex digits */
36 Converts string of hexadecimal digits (including optonal 0x or 0X into its equivalent integer value.
37 The allowable digits are 0-9, a-f, A-F.
41 int htoi(const char s[])
44 int i = 0;
45 unsigned int ans = 0;
46 int valid = 1;
47 int hexit;
49 // skip over 0x or 0X
50 if (s[i] == '0') {
51 ++i;
52 if (s[i] == 'x' || s[i] == 'X') {
53 ++i;
57 while (valid && s[i] != '\0') {
58 ans = ans * 16;
59 if (s[i] >= '0' && s[i] <= '9') {
60 ans = ans + (s[i] - '0');
61 } else {
62 hexit = hex2int(s[i]);
63 if (hexit == 0) {
64 valid = 0;
65 } else {
66 ans = ans + hexit;
69 ++i;
72 if (!valid) {
73 ans = 0;
76 return ans;
79 /* convert hex chars to integers return integer value */
80 int hex2int(int h)
82 char options[] = { "AaBbCcDdEeFf" };
83 int val = 0;
85 int i;
86 for (i = 0; val == 0 && options[i] != '\0'; i++) {
87 if (h == options[i]) {
88 val = 10 + (i / 2);
92 return val;
96 int main()
99 char *test[] = // declare test as array of pointer to char
101 "0xf01",
102 "0xA",
103 "a",
104 "0xB",
105 "23",
106 "100"
109 int res = 0;
110 int i = 0;
111 for (i = 0; i < 6; i++) {
112 res = htoi(test[i]);
113 printf("%d\n", res);
116 return 0;