On Tue, Jun 10, 2014 at 11:26 AM, John Van Ostrand john@vanostrand.com wrote:
I can create a function that extracts the bits into handy to use values and another to insert the bits back in. I can also use a struct with bit positions.
What would you suggest is the best and portable way to handle this?
I would strongly argue against using structures and bitfields, and instead encourage using helper functions to extract bits.
The structures with bitfields approach can result in nice source code, but it tends to be a minefield of portability (you add the issue of bit order in addition to the regular byte order). And that may not be a huge deal for subsurface where all the current targets are x86, but with hopefully eventually Android ports etc, it's just a bad direction to go down.
Also, bitfields work really badly when the data stream has things like conditional bytes in the middle (which is what communication protocols tend to have), so you easily end up with using bitfields that are just for a particular part of the stream, and then doing byte offsets to get to those bitfields. So you end up with this unholy mess of "structure with bitfields cast at offset X". You're better off with a helper function that says "extract X bits at bit offset Y" instead.
Linus