Hex

A utility for converting binary files to hex strings

Latest Release: 1.2.0

 

About Hex

This script reads in a file and outputs it as a hex string formatted for use in, for example, Electric Imp Squirrel applications.

For example, say you have the file sample.png which you wish to serve from an agent. As the agent has no file system, you can’t simply upload the image file. Instead, you store the image as a string which the agent returns upon request and includes the header:

{ "Content-Type": "image/png" }

You use Hex to convert sample.png to the string which your agent will serve. At the command line enter:

$ hex.py sample.png

and the following output will be generated:

\x89\x50\x4E\x47\x0D\x0A\x1A\x0A\x00\x00\x00\x0D\x49\x48\x44\x52\x00\x00\x00\x80\x00\x00
\x00\x80\x08\x06\x00\x00\x00\xC3\x3E\x61\xCB\x00\x00\x00\x04\x67\x41\x4D\x41\x00\x00\xB1

. . .

\x35\x17\x00\x26\xDE\x21\x48\xD4\x6E\x05\x8A\xD5\x7E\xBD\xCD\xB4\x0E\x07\x2B\x18\xEA\x8A
\xFE\x0F\x65\x2D\x5F\x51\xE4\x02\x3B\x28\x00\x00\x00\x00\x49\x45\x4E\x44\xAE\x42\x60\x82

The above listing has been truncated, but in the real world all of the values can be selected, copied and pasted into a string, or the output redirected to a file:

$ hex.py sample.png > string.nut

If you have multiples files to convert, just run Hex without specifying a file name; it will convert all suitable files in the working directory.

The script maintains a list of files extensions which it will ignore during processing. By default, these are .pxm, .py, .txt, .text, .html, .md and .markdown. You can add other extensions to the list by passing them as an argument to the -a / --add switch. Add a single file extension or an unspaced list of comma-separated extensions:

$ hex.py -a pdf
$ hex.py -a pdf,rtf,csv

You can use the -r / --remove switch to remove extensions you have added.

The -v / --verbose switch to show more information during conversion.

Hint Using verbose mode makes it easier to identify the hex output from each of multiple files.


Source Code

You can view Hex’s source code at GitHub.


Release Notes

  • 1.2.0 31 December 2020
    • Write output data to stdout.
    • Write all messages to stderr.
    • Remove old code.
  • 1.1.1 09 April 2019
    • Code styling, optimisation improvements.
  • 1.1.0 22 March 2019
    • Initial public release.

Related Software


smittytonesmittytone
Site and software copyright © 2024, Tony Smith