-
Notifications
You must be signed in to change notification settings - Fork 320
/
ch-2.c
106 lines (93 loc) · 2.27 KB
/
ch-2.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# include <stdlib.h>
# include <stdio.h>
# include <string.h>
# include <unistd.h>
/*
* See https://theweeklychallenge.org/blog/perl-weekly-challenge-002
*/
/*
* Run as: cc -o ch-2.o ch-2.c; ./ch-2.o {-f | -t} < input-file
*
* -f: Translate from base 35 to base 10
* -t: Translate to base 35 from base 35
*/
int BASE = 35;
/*
* Convert from base 35 to base 10
*/
long long from_base (char * number) {
long long out = 0;
while (* number) {
char ch = * number ++;
int n = ch <= '9' ? ch - '0' : ch - 'A' + 10;
out *= BASE;
out += n;
}
return (out);
}
/*
* Convert to base 35 from base 10
*/
char * to_base (long long number) {
char * out;
if ((out = (char *) malloc (64 * sizeof (char))) == NULL) {
fprintf (stderr, "Out of memory\n");
exit (1);
}
size_t i = 0;
while (number > 0) {
int rest = number % BASE;
out [i ++] = rest < 10 ? '0' + rest
: 'A' + rest - 10;
number = number / BASE;
}
out [i] = '\0';
/*
* Reverse the string
*/
for (size_t j = 0; 2 * j < i; j ++) {
char t = out [j];
out [j] = out [i - j - 1];
out [i - j - 1] = t;
}
return (out);
}
int main (int argc, char ** argv) {
char * line = NULL;
size_t len = 0;
size_t strlen;
int do_to_base = 0;
int do_from_base = 0;
char ch;
/*
* Parse and validate options
*/
while ((ch = getopt (argc, argv, "tf")) != -1) {
switch (ch) {
case 't':
do_to_base = 1;
break;
case 'f':
do_from_base = 1;
break;
}
}
if (do_to_base + do_from_base != 1) {
fprintf (stderr, "Need exactly one of -f or -t options\n");
exit (1);
}
while ((strlen = getline (&line, &len, stdin)) != -1) {
line [strlen - 1] = '\0'; /* Chop off newline */
if (do_from_base) {
printf ("%lld\n", from_base (line));
}
if (do_to_base) {
char * out = to_base (atoll (line));
printf ("%s\n", out);
free (out);
}
char * line_ptr = line;
}
free (line);
return (0);
}