Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
CTCaer
GitHub Repository: CTCaer/hekate
Path: blob/master/tools/bin2c/bin2c.c
1476 views
1
/*
2
* This is bin2c program, which allows you to convert binary file to
3
* C language array, for use as embedded resource, for instance you can
4
* embed graphics or audio file directly into your program.
5
* This is public domain software, use it on your own risk.
6
* Contact Serge Fukanchik at [email protected] if you have any questions.
7
*/
8
9
#include <stdio.h>
10
#include <stdlib.h>
11
#include <string.h>
12
#include <ctype.h>
13
#include <unistd.h>
14
15
/* Replace . with _ */
16
char*
17
make_ident ( char* name )
18
{
19
char* ret;
20
char* p;
21
22
ret = strdup ( name );
23
24
for ( p = ret; p[0]; p++ )
25
{
26
if ( !isalnum ( p[0] ) ) p[0] = '_';
27
}
28
return ret;
29
}
30
31
int
32
main ( int argc, char* argv[] )
33
{
34
unsigned char buf[BUFSIZ];
35
char* ident;
36
FILE *fd;
37
size_t size, i, total, blksize = BUFSIZ;
38
int need_comma = 0;
39
40
if ( argc != 2 )
41
{
42
fprintf ( stderr, "Usage: %s binary_file > output_file\n", argv[0] );
43
return -1;
44
}
45
46
fd = fopen ( argv[1], "rb" );
47
if ( fd == NULL )
48
{
49
fprintf ( stderr, "%s: can't open %s for reading\n", argv[0], argv[1] );
50
return -1;
51
}
52
53
fseek(fd, 0, SEEK_END);
54
size = ftell(fd);
55
rewind(fd);
56
57
ident = make_ident ( argv[1] );
58
59
printf ( "static const unsigned char __attribute__((section (\"._%s\"))) %s[] = {", ident, ident );
60
for ( total = 0; total < size; )
61
{
62
if ( size - total < blksize ) blksize = size - total;
63
if ( fread ( buf, 1, blksize, fd ) != blksize )
64
{
65
fprintf ( stderr, "%s: file read error\n", argv[0] );
66
return -1;
67
}
68
for ( i = 0; i < blksize; i++ )
69
{
70
if ( need_comma ) printf ( ", " );
71
else need_comma = 1;
72
if ( ( total % 11 ) == 0 ) printf ( "\n\t" );
73
printf ( "0x%.2x", buf[i] );
74
total++;
75
}
76
}
77
printf ( "\n};\n" );
78
79
fclose ( fd );
80
free ( ident );
81
82
return 0;
83
}
84
85