-
Notifications
You must be signed in to change notification settings - Fork 0
/
bin2c.cpp
77 lines (64 loc) · 1.91 KB
/
bin2c.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
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
std::vector<unsigned char> readFile(const std::string &filename)
{
std::ifstream file(filename, std::ios::binary);
if (!file)
{
throw std::runtime_error("Failed to open file: " + filename);
}
// Determine the file size
file.seekg(0, std::ios::end);
std::streampos fileSize = file.tellg();
file.seekg(0, std::ios::beg);
// Read the file into a vector
std::vector<unsigned char> buffer(fileSize);
file.read(reinterpret_cast<char *>(buffer.data()), fileSize);
return buffer;
}
void writeFile(const std::string &filename, const std::vector<unsigned char> &data)
{
std::ofstream file(filename);
if (!file)
{
throw std::runtime_error("Failed to create file: " + filename);
}
// Write the array declaration to the file
file << "unsigned char data[" << data.size() << "] = { ";
// Write the hex array to the file
for (size_t i = 0; i < data.size(); i++)
{
file << "0x" << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(data[i]);
if (i != data.size() - 1)
{
file << ", ";
}
}
file << " };\n";
}
int main(int argc, char *argv[])
{
if (argc != 3)
{
std::cerr << "Usage: " << argv[0] << " <input_file> <output_file>" << std::endl;
return 1;
}
std::string inputFile = argv[1];
std::string outputFile = argv[2];
try
{
// Read the binary file
std::vector<unsigned char> binaryData = readFile(inputFile);
// Write the hex array and its length to a new file
writeFile(outputFile, binaryData);
std::cout << "Hex array and its length successfully generated in " << outputFile << std::endl;
}
catch (const std::exception &e)
{
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
return 0;
}