Go Down

Topic: multiplication and division: avoiding overflow (Read 858 times) previous topic - next topic

_guybrush_

Let's say I have the following code:

Code: [Select]


byte a; //a number between 0 and 100
byte b;
byte c1,c2;

c1=a*b/100;
c2=byte(word(a)*word(b)/100);


Because a is constrained to 0,100, the value of c will between 0 and 255, so it fits in a byte.

What is the proper way to calculate c=a*b/100;
Is it the possibility c1? If I remember correctly, multiplications are executed before divisions in C, so we have c1=(a*b)/100, but here, even though c1 holds in a byte, (a*b) can exceed this limit (before the result is divided by 100), so should I explicitly cast a and b to words (what I did for c2) before doing the multiplication?
Recasting to byte is probably not useful, but is it necessary to cast a and b to words so that the temporary results a*b doesn't cause overflow?

Thanks!

PaulS

Quote
Let's say I have the following code:
Let's not. You are trying to multiply a by an undefined value.

Quote
Because a is constrained to 0,100, the value of c will between 0 and 255, so it fits in a byte.
Not unless b is constrained to be between 0 and 2. If b is larger than 2, the result of the multiplication will overflow.

Quote
If I remember correctly, multiplications are executed before divisions in C
Not unless that is the order of operations, or parentheses are used. The operations are performed left to right.

Quote
so should I explicitly cast a and b to words
Not unless you work for Microsoft. Words have no place on the Arduino. Cast to int or unsigned int - standard types, not bastardized types like word.
The art of getting good answers lies in asking good questions.

Magician

Quote
is it necessary to cast a and b to words so that the temporary results a*b doesn't cause overflow?
Not necessary, arduino does int8_t x int8_t = int16_t, overflow not happened with 8-bits variables.

_guybrush_

@Magician: Thank you very much for your very concise and clear answer, this is exactly what I wanted to know.

@PaulS: I don't see any reason to be so negative. I probably shouldn't have placed the few lines I wrote with the code tag, because as you point out, variables are not defined, but it was of course implied that other lines of code go in between, and that it was a general question and not a specific example. Sit down, take a coffee and relax.

Go Up