Working with bits

Jef Driesen jef at libdivecomputer.org
Tue Jun 10 23:22:40 PDT 2014


On 2014-06-10 20:44, Linus Torvalds wrote:
> On Tue, Jun 10, 2014 at 11:26 AM, John Van Ostrand 
> <john at 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.

I can only agree with Linus. For libdivecomputer, I'll simply not accept 
non-portable code (with only one small exception in the platform 
specific parts). Thus no structures with bitfields. Most bit 
manipulations aren't that ugly, and usually all you need is a simple 
mask with a right shift:

value = (byte & 0xAB) >> C;

Jef


More information about the devel mailing list