Search code examples
bitmapbit-manipulationbitbitarraybitvector

Bit alignment, 8-bools-in-1


I'm trying to compile the following code:

union Bool
{
  bool b[8] : 8; // (1)
  bool b0,b1,b2,b3,b4,b5,b6,b7 : 1;
};

However the line (1) doesn't compile, whats the syntax for bit aligning an array?


Solution

  • You can't declare an array of bits in C.

    The concept of an array is based on a pointer, and you can only have pointers to bytes, not to individual bits within a byte. C Bit fields allow you to pack integer components into less memory than the compiler would by default. An array isn't an integer, so you can't pack an array into a bit field. If you want to read up on the standard, you can find it at ISO/IEC 9899 - Programming languages - C (look for §6.7.2.1).

    If you need speed, you could use a union of an array of bools, and if you need a compact memory footprint, you could define macros to provide more convenient access to your bit fields.