Tcl's [binary scan] and the Go Challenge 1

Published , updated

In the programming language Tcl the command [binary scan] decodes binary data according to a format string. For example,

binary scan $data {cu4 f1 a*} fourBytes aFloat remainder

will read four unsigned 8-bit integers from the string data and put them into the variable fourBytes, then read one 32-bit floating point number and put it in aFloat, then, finally, put the remaining string in remainder (without altering data itself).

I immediately thought of this command when reading the Go Challenge 1, a programming challenge that involves reverse engineering a binary file format and writing a program that extracts data from it. Indeed, the command proved very useful in solving the challenge.

In the following GitHub gist is my solution to the challenge. It shows how to use [binary scan] with commentary explaining how Tcl works along the way. The solution passes go test. With it I hope to illustrate why I think [binary scan] and its counterpart [binary format] are a great way to manipulate binary data from a simple hashbang script.

The challenge is fun, so if you haven't solved it yourself I encourage you to go (no pun intended) and try it before you read my solution lest it spoils some of the fun for you.

A "thanks" goes out to Poor Yorick and @rich123 for suggestions that helped improve this code and its comments.