Question

I am having trouble finding information on the proper handling of variables during binary arithmetic. I am currently working on implementing an algorithm on an Atmel ATTiny84 microcontroller. I am coding it in C++.

The issues I am having is that with Binary Arithmetic you could end up in overflow or you could end up with a variable size that is larger than the value being stored in it. I apologize if this is confusing let me explain with an example.

uint16_t A=500;
uint8_t B=8;
uint32_t C;

C=A*B;

From what I've learned via google search, if you multiply a variable of size M by a variable of size N it results in a variable of size M+N. In the above case C=4000 but M+N is 24. The value 4000 however can fit in 16 bits. Can I simply declare C as 16 bit or does it have to be 32 bit as shown above?

uint16_t A=500;
uint8_t B=8;
uint16_t C;
C=A*B;

If I do have to store 4000 in a variable that is 32 bits, can I simply transfer it to a variable that is 16 bits by the following

uint16_t D;
uint32_t C
C=4000;
D=C; 

Thanks in advance for the help.

Was it helpful?

Solution

Multiplication won't return a larger type than the two operands unless you specifically tell it to. The operation will convert all variables to the largest width and then multiply. When you multiply a 16 bit int by an 8 bit int, the 8 bit int will be converted to a 16 bit int, and then the two will be multiplied. Although mathematically the result can be larger than 16 bits, the operation will only return a 16 bit number. If the result cannot fit in 16 bits of space, then an overflow flag will be set (check your microcontroller manual to see how to check that).

In your case, the operation will return 4000, which can be stored in a 16 bit variable, so that is fine.

OTHER TIPS

uint16_t A=500;
uint8_t B=8;
uint32_t C;

C=A*B;

It will promote a and b to the size of C then do the math.

uint16_t A=500;
uint8_t B=8;
uint16_t C;
C=A*B;

It will promote a and b to the size of C then do the math.

uint16_t D;
uint32_t C;
C=4000;
D=C; 

You may or may not get a warning that you are trying to shove 32 bits into 16.

D=(uint16_t)C; 

Will clip off the lower 16 bits without a warning. Both cases result in the lower 16 bits going into D.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top