Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Convert a Binary File to a Hex Encoded Text File

4.78/5 (9 votes)
5 Dec 2014CPOL 62.6K   2.1K  
A small command line utility to convert a binary file to hex encoded text file

Introduction

When writing some shared code that depends on resources, I find it is often easier to include the resource in the source code rather then supplying a separate resource file that needs to be kept track of and added separately to a project. The thing is the resource needs to be in the source in Hex format so it can be accessed as a byte array. But the conversion can be a bit of a pain unless you have a little utility to do the work for you. Presented here is a command line utility that does just that.

Using the Code

Bin2Text Help Screen.
Usage: Bin2Text [-c Count] [-h] [-s Skip] Input Output

Options:
        -c        Number of bytes to convert to text
         Count  = Number of bytes to convert, '-1' goes to end of file
        -h        Display Usage Information (This screen)
        -s        Skip the first number of bytes in the input file
         Skip   = Number of bytes to skip

Arguments:
        Input   = File to read
        Output  = File to write

  (c) 2015 PJ Arends

The input file can be any file at all. The output file will be a text file where the data is written out in comma separated hexadecimal format, with 16 bytes per line. For example, I have a 5 x 5 pixel 24bit colour bitmap called sample.bmp.

Bin2Text Sample.bmp Sample.txt

And the resulting file Sample.txt:

0x42, 0x4D, 0x86, 0x00,   0x00, 0x00, 0x00, 0x00,   0x00, 0x00, 0x36, 0x00,   0x00, 0x00, 0x28, 0x00, 
0x00, 0x00, 0x05, 0x00,   0x00, 0x00, 0x05, 0x00,   0x00, 0x00, 0x01, 0x00,   0x18, 0x00, 0x00, 0x00, 
0x00, 0x00, 0x50, 0x00,   0x00, 0x00, 0x00, 0x00,   0x00, 0x00, 0x00, 0x00,   0x00, 0x00, 0x00, 0x00, 
0x00, 0x00, 0x00, 0x00,   0x00, 0x00, 0x57, 0x7A,   0xB9, 0x57, 0x7A, 0xB9,   0xC9, 0xAE, 0xFF, 0xC9, 
0xAE, 0xFF, 0x0E, 0xC9,   0xFF, 0x00, 0x15, 0x00,   0x88, 0x57, 0x7A, 0xB9,   0x57, 0x7A, 0xB9, 0xC9, 
0xAE, 0xFF, 0xC9, 0xAE,   0xFF, 0x00, 0x15, 0x00,   0x88, 0x15, 0x00, 0x88,   0x57, 0x7A, 0xB9, 0x57, 
0x7A, 0xB9, 0xC9, 0xAE,   0xFF, 0x00, 0x24, 0x1C,   0xED, 0x15, 0x00, 0x88,   0x15, 0x00, 0x88, 0x57, 
0x7A, 0xB9, 0x57, 0x7A,   0xB9, 0x00, 0x24, 0x1C,   0xED, 0x24, 0x1C, 0xED,   0x15, 0x00, 0x88, 0x15, 
0x00, 0x88, 0x57, 0x7A,   0xB9, 0x00, 

Now the output file can be copy and pasted into my source code.

Updates

2014-12-05 Fixed "Too few arguments" bug when -h passed to program
2014-11-22 Initial posting to CodeProject

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)