views:

292

answers:

1

I've been given the arduous task of parsing some incoming UDP packets from a source into an appropriate Java representation. The kicker is the data held within the packets are not byte aligned. In an effort to make the protocol as tight as possible, there are a number of bit fields indicating the presence or absence of data fields.

For example, at bit index 34 you may find a 24 bit field that should be converted to a float. Bit index 110 may be a flag indicating that the next 3 fields are each 5 and 6 bit values containing the hour, minute, and second of the day. (These are just made up by me but are representative of what the spec says). These packets are probably a few hundred bits long.

The spec is not likely to change, but it's completely possible that I'll be asked to decode other similar packet formats.

I can certainly bit shift and mask as needed, but I'm worried about ending up in bit shift hell and then drowning in it when more packet formats are discovered.

I'd love to hear any suggestions on best practices or Java libraries that may make the task more manageable.

+2  A: 

Decoding QR codes is much the same exercise in reading a couple bits at a time, completely unaligned. Here's what I wrote to handle it -- maybe you can just reuse this.

http://code.google.com/p/zxing/source/browse/trunk/core/src/com/google/zxing/common/BitSource.java

Sean Owen
Nice, +1. Once comment though - your class is **not** thread-safe; to be so it would need to be safe for multiple threads to use the *same instance* concurrently. Requiring a separate instance per thread is not thread-safe.
Software Monkey
Indeed, thanks for the tip.
Jason Nichols
I agree, not sure who changed that comment. Separate per-thread instances can be used safely (i.e. there are no 'static' members that would confound that) so I think that was what was at least intended.
Sean Owen