How to dump a binary file as a C/C++ string literal

chexdumpxxd

I have a binary file I would like to include in my C source code (temporarily, for testing purposes) so I would like to obtain the file contents as a C string, something like this:

\x01\x02\x03\x04

Is this possible, perhaps by using the od or hexdump utilities? While not necessary, if the string can wrap to the next line every 16 input bytes, and include double-quotes at the start and end of each line, that would be even nicer!

I am aware that the string will have embedded nulls (\x00) so I will need to specify the length of the string in the code, to prevent these bytes from terminating the string early.

Best Answer

You can almost do what you want with hexdump, but I can't figure out how to get quotes & single backslashes into the format string. So I do a little post-processing with sed. As a bonus, I've also indented each line by 4 spaces. :)

hexdump -e '16/1 "_x%02X" "\n"' filename | sed 's/_/\\/g; s/.*/    "&"/'

Edit

As Cengiz Can pointed out, the above command line doesn't cope well with short data lines. So here's a new improved version:

hexdump -e '16/1 "_x%02X" "\n"' filename | sed 's/_/\\/g; s/\\x  //g; s/.*/    "&"/'

As Malvineous mentions in the comments, we also need to pass the -v verbose option to hexdump to prevent it from abbreviating long runs of identical bytes to *.

hexdump -v -e '16/1 "_x%02X" "\n"' filename | sed 's/_/\\/g; s/\\x  //g; s/.*/    "&"/'
Related Question