16bit math


I am trying to perform a math operation on my UNO and I get the wrong number.

unsigned int A = 1249; unsigned int B = 79; unsigned int C = 0;

C = A * B / 100

The result I get is C = 331, but I was expecting 986.

Is my problem caused by Arduino having an 8-bit processor and I am performing math with 16-bit number? If so, how do I correct this problem?

It's because the result of 1249 * 79 = 98671 is too large to fit into a 16-bit integer. You have to force the computation to use 32-bit (long) integer arithmetic and then it will work.

C = (long)A * B / 100;


So simple :) Thanks.