title: Bit Shifting, Masking or a Bit Field Struct?
body: <p>I'm new to working with bits.  I'm trying to work with an existing protocol, which can send three different types of messages.</p>
  
  <p>Type 1 is a 16-bit structure:</p>
  
  <pre><code>struct digital 
  {
   unsigned int type:2;
   unsigned int highlow:1;
   unsigned int sig1:5;
   unsigned int :1;
   unsigned int sig2:7;
  };
  </code></pre>
  
  <p>The first two bits (type, in my struct above) are always 1 0 .  The third bit, highlow, determines whether the signal is on or off, and sig1 + sig2 together define the 12-bit index of the signal.  This index is split across the two bytes by a 0, which is always in bit 7.</p>
  
  <p>Type 2 is a 32-bit structure.  It has a 2-bit type, a 10-bit index and a 16-bit value, interspersed with 0's at positions 27, 23, 15 &amp; 7.  A bit-field struct representation would like something like this:</p>
  
  <pre><code>struct analog 
  {
   unsigned int type:2;
   unsigned int val1:2;
   unsigned int :1;
   unsigned int sig1:3;
   unsigned int :1;
   unsigned int sig2:7;
   unsigned int :1;
   unsigned int val2:7;
   unsigned int :1;
   unsigned int val3:7;
  };
  </code></pre>
  
  <p>sig1 &amp; sig2 together form the 10-bit index.  val1 + val2 + val3 together form the 16-bit value of the signal at the 10-bit index.</p>
  
  <p>If I understand how to work with the first two structs, I think I can figure out the third.</p>
  
  <p>My question is, is there a way to assign a single value and have the program work out the bits that need to go into val1, val2 and val3?  </p>
  
  <p>I've read about bit shifting, bit-field structs and padding with 0's.  The struct seems like the way to go, but I'm not sure how to implement it.  None of the examples of bit-packing that I've seen have values that are split the way these are.  Ultimately, I'd like to be able to create an analog struct, assign an index (i = 252) and a value (v = 32768) and be done with it.  </p>
  
  <p>If someone could suggest the appropriate method or provide a link to a similar sample, I'd greatly appreciate it.  If it matters, this code will be incorporated into a larger Objective-C app.</p>
  
  <p>Thanks.</p>
  
  <p>Brad</p>