Strange results of multiplying the variable uint16_t by a number

I have a very simple piece of C code that gives me a weird result. I am developing a simple wireless touch sensor network application for Micaz mixes. It seems to have ATmega128L 8 bit AVR microprocessors. I use AVR studio to write and compile code.

uint16_t myvariable;
uint16_t myresult;
myresult = myvariable*256;

When myvariable is 3, I found that myresult always reset to 512. Just wondering why this works like this. I assume that a mixture of such a literal of 256 and uint16_t magically causes a problem. But I do not know why. Can someone give a detailed explanation for this? Appreciate any help!

A more detailed source code is as follows.

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 && !MsgSent) {
          // If ACK received and a new message not sent yet,
          // send a new message on sending node.
        }

        else if(!AckReceived && 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];  
        }

      }
    }           

}

, , , . !

myresult[thisnodeid] = 256*myvariable[1] + myvariable[0]; 

myvariable [1] = 3, myvariable [0] = 0, myresult [] = 512. Looks 768 reset 512. .

+5
1

:

#include <stdio.h>
#include <string.h>
#include <stdint.h>
#define MAX_SENDERS 10
static uint16_t myvariable[2];
static uint8_t AckMsg[32];
uint16_t myresult[MAX_SENDERS];
main()
{
    AckMsg[0] = 0;
    AckMsg[1] = 3;
    myvariable[0] = AckMsg[0];
    myvariable[1] = AckMsg[1];
    myresult[0] = 256*myvariable[1] + myvariable[0];  
    printf("%d", (int)myresult[0]);
}

, , :

myvariable[0] = AckMsg[0];
myvariable[1] = AckMsg[1];
// Bug!!!, variable overflowed.
myresult[thisnodeid] = 256*myvariable[1] + myvariable[0]; 

:

uint16_t tmp;
myvariable[0] = AckMsg[0];
myvariable[1] = AckMsg[1];
tmp = 256*myvariable[1] + myvariable[0]; 
myresult[thisnodeid] = 256*myvariable[1] + myvariable[0]; 
printf("%d %d\n", (int)(AckMsg[0]), (int)(AckMsg[1]));
printf("%d %d\n", (int)(thisnodeid), (int)(MAX_SENDERS));
printf("%d %d\n", (int)(myvariable[0]), (int)(myvariable[1]));
printf("%d %d\n", (int)(tmp), (int)(myresult[thisnodeid]));

.

- , :

uint16_t i = 0;
uint16_t n = 255;
myresult[thisnodeid] += myvariable[1];
while (i != n) {
    myresult[thisnodeid] += myvariable[1];
    i += 1;
}
myresult[thisnodeid] += myvariable[0]; 

, , overlow, , 255, myresult.

+1

All Articles