Created
November 20, 2017 16:47
-
-
Save jynik/5687f5b3e7691e8d2b1b559e32c8ab70 to your computer and use it in GitHub Desktop.
carray - Print a binary file as a C array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Print the contents of a binary file as a C array. | |
* | |
* SPDX License Identifier: MIT | |
* (C) 2017 Jon Szymaniak <[email protected]> | |
*/ | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <errno.h> | |
static const char usage[] = | |
"Usage: %s <binary file> [type] [name]\n" | |
"\n" | |
"Prints the contents of <binary file> as a C array, of type [type] and \n" | |
"named [name], to stdout.Each input byte will be a separate array \n" | |
"element. The defaults are: type=char, name=data\n" | |
"\n" | |
"Example:\n" | |
" $ carray myfile.bin uint8_t mydata\n" | |
"\n"; | |
static const char header[] = "static const %s %s[] = {"; | |
static const char footer[] = "\n};\n\nstatic const size_t %s_len = %zd;\n\n"; | |
int main(int argc, char *argv[]) | |
{ | |
const char default_name[] = "data"; | |
const char default_type[] = "uint8_t"; | |
const char *type = default_type; | |
const char *name = default_name; | |
FILE *in; | |
size_t addr, n_read, col, i; | |
unsigned char buf[64 * 1024]; | |
if (argc < 2 || argc > 5) { | |
fprintf(stderr, usage, argv[0]); | |
return EXIT_FAILURE; | |
} | |
if (argc >= 3) { | |
type = argv[2]; | |
} | |
if (argc >= 4) { | |
name = argv[3]; | |
} | |
in = fopen(argv[1], "rb"); | |
if (!in) { | |
fprintf(stderr, "Failed to open %s: %s\n", argv[1], strerror(errno)); | |
return EXIT_FAILURE; | |
} | |
printf(header, type, name); | |
addr = col = 0; | |
n_read = fread(buf, 1, sizeof(buf), in); | |
while (n_read) { | |
for (i = 0; i < n_read; i++, addr++) { | |
const unsigned char b = buf[addr]; | |
switch (col) { | |
case 0: | |
printf("\n /* %08x */ 0x%02x", | |
(unsigned int) addr, b); | |
break; | |
case 4: | |
printf(", 0x%02x", b); | |
break; | |
case 7: | |
printf(", 0x%02x,", b); | |
break; | |
default: | |
printf(", 0x%02x", b); | |
} | |
col = (col + 1) & 0x7; | |
} | |
n_read = fread(buf, 1, sizeof(buf), in); | |
} | |
printf(footer, name, addr); | |
fclose(in); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
man xxd