-
Notifications
You must be signed in to change notification settings - Fork 0
/
bin2h.cpp
66 lines (54 loc) · 1.52 KB
/
bin2h.cpp
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 <iostream>
#include <fstream>
#include <string>
void print_usage()
{
std::cerr << "Usage: bin2h input.bin output.header symbol_name\n";
}
int main(int argc, char **argv)
{
if (argc != 4)
{
print_usage();
return EXIT_FAILURE;
}
std::ifstream inFile(argv[1], std::ios::in);
if (!inFile)
{
std::cerr << "Failed to open input file \"" << argv[1] << "\"\n";
return EXIT_FAILURE;
}
std::ofstream outFile(argv[2], std::ios::out);
std::string symName(argv[3]);
std::string sanitisedFileName(argv[2]);
std::string allowedChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_");
size_t pos = sanitisedFileName.find_first_not_of(allowedChars, 0);
while (pos != std::string::npos)
{
sanitisedFileName[pos] = '_';
pos = sanitisedFileName.find_first_not_of(allowedChars, pos);
}
inFile.seekg(0, std::ios::end);
size_t fileSize = inFile.tellg();
inFile.seekg(0, std::ios::beg);
outFile << "/* AUTOGENERATED HEADER */\n"
<< "#ifndef __" << sanitisedFileName << "\n"
<< "#define __" << sanitisedFileName << "\n";
outFile << "struct {\n"
<< "\tunsigned int size;\n"
<< "\tunsigned char data[" << fileSize << "];\n"
<< "} " << symName << " = {\n"
<< "\t.size = " << fileSize << ",\n"
<< "\t.data = {";
for (size_t b = 0; b < fileSize ;b++)
{
unsigned char byte;
if (b%10 == 0)
outFile << "\n\t";
inFile.read((char*)&byte, 1);
outFile << std::hex << "0x" << (unsigned int)byte << ", ";
}
outFile << "\t}\n"
<< "};\n";
outFile << "#endif\n";
}