Search code examples
cfixed-point

Use fractional part in fixed point calculation


I have a calculation which is the following:

1472 / 48 = 30.666667
(30 * 48) = 1440
(0.666667 * 48) = 32

So the numbers I nead are 1440 and 32, which can be calculated with the real part and the fractional part of the first calculation. Using the following piece of code I find the real part, but the fractional part is on a scale.

#define SHIFT_AMOUNT    16
// 2 bytes is used to map divisions
#define SCALE_FACTOR    65535 // (2^16)
#define SHIFT_MASK      ((1 << SHIFT_AMOUNT) - 1)

uint32_t total_msgs = DATA_LENGTH << SHIFT_AMOUNT;
total_msgs /= PAYLOAD_SIZE;

uint8_t real_part = total_msgs >> SHIFT_AMOUNT; // 30
uint32_t decimal_part = total_msgs & SHIFT_MASK; // 43690

Now for the last calculation I'm stuck. How do I get 32 from 43690 (which really is ((43690 / 65535) = 0.666667) ?


Solution

  • The usual way to solve this problem is the % operator:

    quotient = DATA_LENGTH / PAYLOAD_SIZE;
    fraction = DATA_LENGTH % PAYLOAD_SIZE;