Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Utility for Header-fying a Binary File 1

Status
Not open for further replies.

chipperMDW

Programmer
Mar 24, 2002
1,268
US
Can someone point me to a utility that can convert a binary file into a C (or C++) header? A Unix utility would be preferred, but a Windows one will work, too.

For example, such a utility might generate output similar to the following:

Code:
#ifndef XXXXX
#define XXXXX

const char xxxxx_data = "\005\000\003\062\145\000\003"
                        "\064\061\210\005\112\421\000";

#endif
 
How about compiler's restriction on initialization list (or string literal)length? Moreover: a declaration with initialization is a definition, but definitions are placed in .c files, not in headers (multiple definitions problem)...

 
For short binary files, the length restriction doesn't matter much. And I'm not sure, but the GNU people seem to hate arbitrary limits, so my GCC could probably handle a file larger than whatever the C++ Standard gives as a max.


This would not be a normal header to be included in several translation units; it would be included in a single source file.

I could call it an "#includable file" and give it a suffix of [tt].inc[/tt] if the idea of a definition in a header file is unacceptable; it would be the same idea, however.


At any rate, it seems like [tt]bin2h[/tt] is the utility I was looking for, but I seem to be able to find only a Windows version of the tool. If anyone knows where to find a Unix version of [tt]bin2h[/tt], please let me know.
 
Well I would go with something like
Code:
unsigned char data[] = {
#include "binary.inc"
};

This handy perl script can generate the data with say
[tt]hex_to_c.pl file.dat > binary.inc[/tt]

The script
Code:
#!/usr/bin/perl -w
use strict;

$/ = undef;
my @bytes = unpack("C*",<>);
my $len = $#bytes;

for ( my $i = 0 ; $i < $len ; $i++ ) {
  printf( "0x%02x, ", $bytes[$i] );
  print "\n" if ( ($i+1) % 16 == 0 );
}
print "\n";

--
 
Thanks.

I'm just a little surprised that the GNU people made something like [tt]bin2h[/tt] for Microsoft systems, but no equivalent for GNU systems... it must be in some package somewhere I haven't found, yet.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top