Recently I needed to write some code to parse a binary protocol in PHP. Given an ASCII hex string representation of the message, I needed to pull off bits and bytes, using them in lots of different ways.

The problem was that I had to read a byte at a time from the hex string, then manually shift bits each time to get the desired values. That got confusing fast! So to make things easier I wrote bit-ratchet, a small class that lets you read bits and bytes from a hex string very simply.

The idea is you create a bit-ratchet object from your hex string. You can then ask that object to read numbers from the data, specifying their length in bits. The bit-ratchet object keeps track of the current position in the data and all the shifting for you.

The library takes care of signed numbers but otherwise leaves processing like scaling numbers to the user. I wanted to avoid creating an overly complicated library like BinData.

It scratched my itch but let me know if you’ve got any ideas about how to expand on the abstraction.

Cheers, Dave

Edit: I’ve since written a much more powerful JavaScript version of this library.