-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathraw2gba.c
89 lines (72 loc) · 2.43 KB
/
raw2gba.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
/* raw2gba.c
* this program converts raw byte files into C header files
* this can be used to load raw signed 8-bit audio data into the Game Boy Advance */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* this keeps the output header file from having very long lines */
#define LINE_LIMIT 11
int main(int argc, char** argv) {
FILE* input;
FILE* output;
int i, length;
if (argc != 2) {
fprintf(stderr, "Usage: raw2gba input.raw\n");
return -1;
}
/* open input file */
input = fopen(argv[1], "r");
if (!input) {
fprintf(stderr, "Error: could not open %s for reading.\n", argv[1]);
return -1;
}
/* see how many bytes it is */
fseek(input, 0, SEEK_END);
length = ftell(input);
fseek(input, 0, SEEK_SET);
/* load all of the bytes into an array */
signed char* bytes = malloc(length * sizeof(signed char));
fread(bytes, length, 1, input);
/* find the base name of the input file w/o extension */
char base[strlen(argv[1]) + 1];
strcpy(base, argv[1]);
base[strlen(argv[1]) - 4] = '\0';
/* open output file which is same name but with .h instead of .raw */
char output_name[strlen(base) + 3];
sprintf(output_name, "%s.h", base);
output = fopen(output_name, "w");
if (!output) {
fprintf(stderr, "Error: could not open %s for reading.\n", output_name);
return -1;
}
/* the name of the array and such is the base name of file, but w/ no direcotries */
char* name = base;
while (strstr(name, "/") != NULL) {
name = strstr(name, "/") + 1;
}
/* dump some preamble */
fprintf(output, "/* %s.h\n * generated by raw2gba */\n\n", name);
fprintf(output, "#define %s_bytes %d\n\n", name, length);
fprintf(output, "const signed char %s [] = {\n ", name);
/* print the first byte */
int line_counter = 1;
fprintf(output, "0x%02X", bytes[0] & 0xff);
for (i = 1; i < length; i++) {
/* print a comma after the last byte */
fprintf(output, ", ");
/* go to a new line if needed */
if (line_counter > LINE_LIMIT) {
fprintf(output, "\n ");
line_counter = 0;
}
/* print the next bytw */
line_counter++;
fprintf(output, "0x%02X", bytes[i] & 0xff);
}
fprintf(output, "\n};\n\n");
/* clean things up */
free(bytes);
fclose(input);
fclose(output);
return 0;
}