Make muldiv() multiplicand signed.

As Andrey correctly pointed out, we need this signed. See:
http://forums.reprap.org/read.php?147,89710,130225#msg-130225
and following posts.
This commit is contained in:
Markus Hitter 2012-06-23 14:23:12 +02:00
parent 7efb895ee3
commit a2f1412aec
2 changed files with 11 additions and 5 deletions

View File

@ -25,13 +25,19 @@
Found on http://stackoverflow.com/questions/4144232/
how-to-calculate-a-times-b-divided-by-c-only-using-32-bit-integer-types-even-i
*/
const uint32_t muldiv(uint32_t multiplicand, uint32_t multiplier,
uint32_t divisor) {
const int32_t muldiv(int32_t multiplicand, uint32_t multiplier,
uint32_t divisor) {
uint32_t quotient = 0;
uint32_t remainder = 0;
uint8_t negative_flag = 0;
uint32_t qn = multiplier / divisor;
uint32_t rn = multiplier % divisor;
if (multiplicand < 0) {
negative_flag = 1;
multiplicand = -multiplicand;
}
while(multiplicand) {
if (multiplicand & 1) {
quotient += qn;
@ -55,6 +61,6 @@ const uint32_t muldiv(uint32_t multiplicand, uint32_t multiplier,
quotient++;
// remainder is valid here, but not returned
return quotient;
return negative_flag ? -((int32_t)quotient) : (int32_t)quotient;
}

View File

@ -5,7 +5,7 @@
// return rounded result of multiplicand * multiplier / divisor
const uint32_t muldiv(uint32_t multiplicand, uint32_t multiplier,
uint32_t divisor);
const int32_t muldiv(int32_t multiplicand, uint32_t multiplier,
uint32_t divisor);
#endif /* _DDA_MATHS_H */