title: AVR GCC - typecasting trouble
body: <p>I'm using an AVR microcontroller to write to a programmable frequency divider chip via the I2C bus.  At certain intervals I'm trying to have the following function is called to update the frequency output of the chip:</p>
  
  <pre><code>void 1077WriteDiv(int16_t data)
  {
      uint8_t upperByte = (uint8_t)((uint16_t)data&gt;&gt;2);
  
      i2c_start(DS1077_BASE_ADDRESS);
      i2c_write(DIVIDE_REGISTER);
      i2c_write(upperByte);
      i2c_write(0x0);
      i2c_stop();
  }
  </code></pre>
  
  <p>I'm trying to get the top 8 bits of a ten bit value in the "data" variable and write it out.  The second "write" command writes the lower 8 bits of the "divide" register on the chip, 0 in this case.</p>
  
  <p>As a test case I'm incrementing the "data" variable (which has to be signed for certain reasons) from zero, shifting it left 2 bits and calling this function each time.  I get garbage out.  However, when I do this:</p>
  
  <pre><code> void 1077WriteDiv(int16_t data)
      {
          //uint8_t upperByte = (uint8_t)((uint16_t)data&gt;&gt;2);
              static uint8_t thing = 0;     
  
          i2c_start(DS1077_BASE_ADDRESS);
          i2c_write(DIVIDE_REGISTER);
          i2c_write(thing++);
          i2c_write(0x0);
          i2c_stop();
      }
  </code></pre>
  
  <p>Everything works as expected.  There's obviously some kind of problem in how I'm shifting and typecasting the original "data" variable, but I've tried all kinds of permutations with the same results.  It would be much appreciated if anyone could point out where I might be going wrong.</p>