Q:

How can I calculate this using integer data types only?

I am trying to program the following in C, using MPLABX IDE and XC8 compiler, for a PIC12 microcontroller. I've programmed neither microcontrollers nor C before, so there are some new things I need to consider. One being that calculations using float types are inefficient on these microcontrollers and should therefore be avoided. Trying to follow that philosophy, I would like to know the best practice for doing a calculation like this:

a = b / c * d

Where:

0 =< a =< d,
0 =< b =< c,
0 =< c,
0 =< d

a, b and c are unsigned 16 bit integers. d can be chosen freely.
I am looking for a good compromise between good legible source code, and efficient compiled code.
I have considered restructuring the equation, but avoiding one problem introduces another:

a = b / c * d

--> b/c will always be 0. Remainder is lost.

a = b * d / c

--> b*d may produce overflow.

A:

You should do the multiplication before the division, using a larger type if there will be overflow.
a = (int)((long long)b * d / c);

If you are doubtful about the sequence of operations you can parenthesise it
a = (int)(((long long)b * d) / c);

although it is unnecessary, because although * and / have the same precendence they are parsed from left to right.
If you want to round the result you can add (or subtract if negative product) half the divisor before dividing.
a = (int)(((long long)b * d + (c >> 1)) / c);

