-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbtoa.c
66 lines (55 loc) · 1.14 KB
/
btoa.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
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
void btoa(FILE *ifp, FILE *ofp){
fseek(ifp, 0L, SEEK_END);
unsigned size = ftell(ifp);
fseek(ifp, 0L, SEEK_SET);
char * input = (char *)malloc(size * sizeof(char));
fread(input, sizeof(char), size, ifp);
char * output = (char *)malloc((size/8)+1 * sizeof(char));
output[0] = '\0';
//manufacture a character
for (unsigned i = 0; i < size; i += 8){
char tmp;
int newChar = 0;
if (input[i] == '1'){
newChar += 128;
}
if (input[i+1] == '1'){
newChar += 64;
}
if (input[i+2] == '1'){
newChar += 32;
}
if (input[i+3] == '1'){
newChar += 16;
}
if (input[i+4] == '1'){
newChar += 8;
}
if (input[i+5] == '1'){
newChar += 4;
}
if (input[i+6] == '1'){
newChar += 2;
}
if (input[i+7] == '1'){
newChar += 1;
}
strcat(output, (char*)&newChar);
}
fprintf(ofp, "%s", output);
}
int main(int argc, char **argv){
if (argc != 3){
fprintf(stderr, "Usage: ./btoa <input> <output>\n");
return -1;
}
FILE *ifp = fopen(argv[1], "r");
FILE *ofp = fopen(argv[2], "w");
btoa(ifp, ofp);
fclose(ifp);
fclose(ofp);
return 0;
}