August 22nd 2011
bit-ratchet, easier binary parsing in PHP
Recently I needed to write some code to parse a binary protocol in PHP. Given a ASCII hex string representation of the message I needed to pull off bits and bytes, using them in lots of different ways.
Problem was that you have to read a byte at a time from the hex string, then manually shift bits each time to get what you want. This gets old and confusing very quickly! To solve this I’ve written 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 of your hex string. You then ask for bits and bytes, signed or not and bit-ratchet provides them whilst keeping track of your current position in the data. Additionally I added a few useful methods allowing you to skip, jump and pull off hex.
Things like scaling numbers are mostly left to the user, the one exception being signed numbers which are handled by bit-ratchet. I wanted to avoid creating a complex library like bindata, in my opinion although it’s great the DSL it provides is constraining. Better to let the user use the host language and as far as possible stay out of the way!
It scratched my itch but let me know if you’ve got any ideas about how to expand on the abstraction.