Added example cbd_rand_dist. Generates random numbers and displays distribution.
[C-Programming-Examples.git] / convert.c
blobd2d1533bd223d193458f3f6fd7e4895c2de20173
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 int ans = 0;
46 int valid = 1;
47 int hexit;
49 // skip over 0x or 0X
50 if(s[i] == '0')
52 ++i;
53 if(s[i] == 'x' || s[i] == 'X'){ ++i; }
56 while(valid && s[i] != '\0')
58 ans = ans * 16;
59 if(s[i] >= '0' && s[i] <= '9')
61 ans = ans + (s[i] - '0');
62 } else {
64 hexit = hex2int(s[i]);
65 if(hexit == 0){ valid = 0; } else { ans = ans + hexit; }
67 ++i;
70 if(!valid) { ans = 0; }
72 return ans;
76 /* convert hex chars to integers return integer value */
77 int hex2int(int h)
79 char options[] = { "AaBbCcDdEeFf" };
80 int val = 0;
82 int i;
83 for(i = 0; val == 0 && options[i] != '\0'; i++)
85 if(h == options[i]) { val = 10 + (i/2); }
88 return val;
92 int main()
95 char *test[] = // declare test as array of pointer to char
97 "0xf01",
98 "0xA",
99 "a",
100 "0xB",
101 "23",
102 "100"
105 int res = 0;
106 int i = 0;
107 for(i = 0; i < 6; i++)
109 res = htoi(test[i]);
110 printf("%d\n", res);
113 return 0;