[Ovmsdev] Bitfields and C Compilers

Tom Saxton tom at idleloop.com
Thu Feb 7 07:41:29 HKT 2013


on 2/6/13 12:12 PM, Michael Balzer wrote:

> "OVMS Development" adds: PIC18F is little endian, i.e. [...] Bit fields are
> packed right to left
>  
>  So, it's LSB first, 0x01 .. 0x80.

Actually bitfield order isn't defined by C/C++ or the processor endianness,
it's completely a compiler choice. Depending on it works great until you
switch to a different compiler, or the compiler changes how it works.

Been there, done that.

>  "Better" will be dependant on your concrete needs. I like to be able to
> access single bits like this due to better readability.
>  
>  But if you need to set or query a larger group of bits, the combined byte
> value will be more readable and perform better.

A good compiler will generate the same code either way, at least it will
with optimizations turned on.

If there's a good reason to manipulate bitfield bits directly, it's much
better to #define (or enum) named constants,

// in the header file, next to the structure definition
#define fdoors1Charge 0x04
#define fdoors1Pilot  0x08

// in the code
car_doors1 |= fdoors1Charge | fdoors1Pilot;

Not only is the code self documenting (no comment needed), you only have to
fix the #defines if/when the compiler changes (conditionally if supplorting
multiple platforms) rather than tracking down every use in the code.

Since this code base is already supporting at least three platforms: PIC,
iPhone, and Android, it's really best not to be depending on compiler
choices. 

    Tom





More information about the OvmsDev mailing list