This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Bitfield

Hello to everyone,
i have this example:

union
{
  struct
  {
    unsigned char x:4;
    unsigned char y:4;
  } nibble;
  unsigned char abyte;
} value;


I'am not sure how to acces to the byte and the two nibble's.
I tried several hours, maybe there's a mistake in my textbook?
Or there is a fatal error in my understanding of struct and union's!

There's an really idioticall way to solve this:
Just toggling thru all permutations of syntax :-(
No, better to ask someone who knows and is willing to help :-)

Parents
  • Bit fields in C differ between implementations. If your code happens to work with one compiler, it may fail with another.
    However, shifts and masking always work. I think, all you need is a few macros:

    #define CHAR2LO(c)          ((c)&0xF)
    #define CHAR2HI(c)          (((c)>>4)&0xF)
    #define NIBBLES2CHAR(lo,hi) ((((hi)&0xF)<<4)|((lo)&0xF))
    #define INSERTLO(c, lo)     (((c)&0xF0)|((lo)&0xF))
    #define INSERTHI(c, hi)     (((c)&0xF)|(((hi)&0xF)<<4))
    


    By the way, that's what the compiler actually does to implement bit fields.

    Regards,
    - mike

Reply
  • Bit fields in C differ between implementations. If your code happens to work with one compiler, it may fail with another.
    However, shifts and masking always work. I think, all you need is a few macros:

    #define CHAR2LO(c)          ((c)&0xF)
    #define CHAR2HI(c)          (((c)>>4)&0xF)
    #define NIBBLES2CHAR(lo,hi) ((((hi)&0xF)<<4)|((lo)&0xF))
    #define INSERTLO(c, lo)     (((c)&0xF0)|((lo)&0xF))
    #define INSERTHI(c, hi)     (((c)&0xF)|(((hi)&0xF)<<4))
    


    By the way, that's what the compiler actually does to implement bit fields.

    Regards,
    - mike

Children
  • "Bit fields in C differ between implementations"

    Also, the ordering of bytes within multi-byte values, and the possibility of extra padding bytes within structures, etc...

  • "By the way, that's what the compiler actually does to implement bit fields."

    In addition to that, if you specify a boolean op and a shift op, the ARM compiler will most likely generate a single machine instruction to perform the bitfield set/clear.

    There is one advantage of using bitfields instead of low-level bit-shift-and-mask though: clarity of code and intention of the programmer.

    As long as you don't assume any physical mapping of the struct to the underlying storage, you can safely rely on the integer promotions of the bitfield to int, i.e., if you have a bitfield of 3 bits, you can safely use its value as a word-extended value to int in a expression.