title: Weird results from multiplying uint16_t variable with a number
body: <p>I have a very simple piece of C code that gives me weird result. I'm developing a simple wireless sensor network application for Micaz motes. It seems to have ATmega128L 8 bit AVR microprocessors. I'm using AVR studio to write and compile the code. </p>
  
  <pre><code>uint16_t myvariable;
  uint16_t myresult;
  myresult = myvariable*256;
  </code></pre>
  
  <p>When myvariable is 3, I found myresult was always reset to 512. Just wondering why it works like this. My guess is, the mixture of such a literal number 256 and uint16_t magically causes the problem. But I don't know why. Could anybody give a detailed explanation on this? Appreciate for any help!</p>
  
  <p>More detailed source code is as follows. </p>
  
  <pre><code>static uint16_t myvariable[2];
  static uint8_t AckMsg[32];
  uint16_t myresult[MAX_SENDERS];
  
  void protocol()  
  {           
      if(thisnodeid != 5){   // sender nodes
        while (1)
        {         
          if(AckReceived &amp;&amp; !MsgSent) {
            // If ACK received and a new message not sent yet,
            // send a new message on sending node.
          }
  
          else if(!AckReceived &amp;&amp; MsgSent)
          {
              lib_radio_receive_timed(16, 32, AckMsg, 120);
              myvariable[0] = AckMsg[0];
              myvariable[1] = AckMsg[1];
              // Bug!!!, variable overflowed.
              myresult[thisnodeid] = 256*myvariable[1] + myvariable[0];  
          }
  
        }
      }           
  
  }
  </code></pre>
  
  <p>What I really want to figure out is, how the compiler compiles following line of code, because I know it's this line of code causes the bug. Thanks in advance for any information!</p>
  
  <pre><code>myresult[thisnodeid] = 256*myvariable[1] + myvariable[0]; 
  </code></pre>
  
  <p>When myvariable[1]=3, myvariable[0]=0, I always get myresult[] = 512. Looks 768 is always reset to 512. Just don't know why.</p>