title: arrays + unions + structs containing bit fields C++
body: <p>I was just playing around with bit fields and came across something that I can't quite figure out how to get around.</p>
  
  <p>(Note about the platform: size of an int = 2bytes, long = 4bytes, long long = 8bytes - thought it worth mentioning as I know it can vary. Also the 'byte' type is defined as an 'unsigned char')</p>
  
  <p>I would like to be able to make an array of two 36 bit variables and put them into a union with an array of 9 bytes. This is what I came up with:</p>
  
  <pre><code>typedef union {
    byte bytes[9];
    struct {
      unsigned long long data:36;
    } integers[2];
  } Colour;
  </code></pre>
  
  <p>I was working on the theory that the compiler would realise there was supposed to be two bitfields as part of the anonymous struct and put them together into the space of 9 bytes. However it turns out that they get aligned at a byte boundary so the union occupies 10 bytes not 9, which makes perfect sense.</p>
  
  <p><strong>The question is then, is there a way to create an array of two bit fields like this?</strong> I considered the 'packed' attribute, but the compiler just ignores it.</p>
  
  <p>While this works as expected (sizeof() returns 9):</p>
  
  <pre><code>typedef union {
    byte bytes[9];
    struct {
      unsigned long long data0:36;
      unsigned long long data1:36;
    } integers;
  } Colour;
  </code></pre>
  
  <p>It would be preferable to have it accessible as an array.</p>
  
  <hr>
  
  <p>Edit:
  Thanks to cdhowie for his explanation of why this won't work.</p>
  
  <p>Fortunately I thought of a way to achieve what I want:</p>
  
  <pre><code>typedef union {
    byte bytes[9];
    struct {
      unsigned long long data0:36;
      unsigned long long data1:36;
      unsigned long long data(byte which){
        return (which?data1:data0);
      }
      void data(byte which, unsigned long long _data){
        if(which){
          data1 = _data;
        } else {
          data0 = _data;
        }
      }
    } integers; 
  
  } Colour; 
  </code></pre>