Charles Keepax's Blog

Atom Feed

Intel HEX Checksums in Vim

If you do any work in the embedded world you have no doubt come across Intel HEX files. Intel HEX files provide a text representation of binary data and are often used for programming of Flash and EEPROM parts. Each line of the file contains a checksum at the end, when manually editing the file updating the checksums is very annoying. To fix this I have written a small bit of vim script to automatically correct said checksum.

The code embedded here will probably not be kept up to date with bug fixes etc. in the future so you are better off getting the latest version from the Mercurial repository.

The simplest way to install the code is to put a copy of the function in your vimrc file. Alternatively, you could load it from another file by putting "source path/filename" into your vimrc file.

The function operates on the current line of text, and is invoked by typing ":call IHexChecksum()" in normal mode. This could be simplified by addeding a key mapping to your vimrc file, such as "map :call IHexChecksum()", which will invoke the function whenever Ctrl-h is pressed. Once invoked the function will check the current line is valid Intel HEX, calculate the checksum, and then replace the last two characters of the line with the corrected value. It is important to note that the checksum is updated rather than two characters being added, such that if you are writing new lines you will want to add in a bogus checksum first. I find myself usually editing small changes into existing lines of a file rather add new lines so updating seemed the logical choice.

The code itself is pretty simple and should be rather self explanatory. First the input line is matched to a regular expression, this checks the line is valid Intel HEX. The regular expression checks for the existance of a colon at the start of the line, that the rest of the line contains an even number of characters all of which are valid hexadecimal characters, and that it is at least 5 bytes long. The checksum is then calculated by reading the input one byte at a time, care is taken to account for overflow whilst twos complimenting the checksum. Finally the line is written back with the last two digits corrected.

Hopefully, someone out there finds this little script as useful as I do. Please feel free to use/edit/pretend it's yours/do whatever with the code, although I would appreciate hearing about any bugs/improvements. I am rather new to using Vim script and suspect the script could be improved somewhat.