Consider the following as a reference implementation:
/* calculates (a * b) / c */
uint32_t muldiv(uint32_t a, uint32_t b, uint32_t c)
{
uint64_t x = a;
If b = 3000000000 => qn = 3000000000, qn*2 will be overflowed. So I edit the code of Sven Marnach.
uint32_t muldiv(uint32_t a, uint32_t b, uint32_t c)
{
uint32_t q = 0; // the quotient
uint32_t r = 0; // the remainder
uint32_t qn = b / c;
uint32_t rn = b % c;
while (a)
{
if (a & 1)
{
q += qn;
if (qn >= UINT32_MAX) {
cout << "CO CO" << endl;
}
r += rn;
if (r >= c)
{
q++;
r -= c;
}
}
a >>= 1;
qn <<= 1;
int temp = rn;
if (rn > INT32_MAX) {
// rn times 2: overflow
rn = UINT32_MAX;// rn
temp = (temp - INT32_MAX) * 2; // find the compensator mean: rn * 2 = UINT32_MAX + temp
qn++;
rn = rn - c + temp;
}
else {
rn <<= 1;
if (rn >= c)
{
qn++;
rn -= c;
}
}
}
//return r;
return q;
}