title: Mapping a number to bit position in C
body: <p>I'm developing an programm running on Atmel AT90CAN128. Connected to this controller there are 40 devices, each with a status (on/off). As I need to report the status of each of this devices to a PC through Serial Communication, I have 40 bits, which define whether the device is on or off. In addition, the PC can turn any of this devices on or off.</p>
  
  <p>So, my first attempt was to create the following struct:</p>
  
  <pre><code>typedef struct {
       unsigned char length;      //!&lt; Data Length
       unsigned data_type;        //!&lt; Data type
       unsigned char data[5];     //!&lt; CAN data array 5 * 8 = 40 bits
  } SERIAL_packet;
  </code></pre>
  
  <p>The problem with this was that the PC will send an <code>unsigned char address</code> telling me the device to turn on/off, so accessing the bit corresponding to that <code>address</code> number turned out to be rather complicated...</p>
  
  <p>So I started looking for options, and I stumbled upon the C99 <code>_Bool</code> type. I thought, great so now I'll just create a <code>_Bool data[40]</code> and I can access the <code>address</code> bit just by indexing my <code>data</code> array. Turns out that in C (or C++) memory mapping needs an entire byte for addressing it. So even if I declare a <code>_Bool</code> the size of that <code>_Bool</code> will be 8 bits which is a problem (it needs to be as fast as possible so the more bits I send the slower it gets, and the PC will be specting 40 bits <em>only</em>) and not very efficient for the communication. So I started looking into Bit Fields, and tried the following:</p>
  
  <pre><code>typedef struct {
      unsigned char length;   //!&lt; Data Length
      unsigned data_type;     //!&lt; Data type
      arrayData data[40]; //!&lt; Data array 5 bytes == 40 bits
  } SERIAL_packet;
  
  typedef struct {
      unsigned char aux : 1;
  } arrayData;
  </code></pre>
  
  <p>And I wonder, is this going to map that <code>data[40]</code> into a consequent memory block with a size of 40 bits (5 bytes)?</p>
  
  <p>If not, is there any obvious solution I'm missing? This doesn't seem like a very complicated thing to do (would be much simpler if there were less than 32 devices so I could use a <code>int</code> and just access through a bit mask).</p>