Search code examples
cmathfloating-pointpic

PIC 16F18 - Excessive program memory usage when multiplying by a floating point number


I have what appears to me a strange problem. It is better illustrated in the attached picture. I am using a PIC 16F18323 with MPLAB and XC8 writing in C. The program memory of the PIC is only 2KB so I need to keep it down as low as possible. The problem is when I try and do a calculation the program memory usage jumps up by 40-50%. The calculation I am doing is simple:

int blue;
int red;
blue = 4 * 1.5;

This is fine and takes up next to zero memory as one would expect. However if I do another, similar calculation, like this:

int blue = 4;
int red;
red = blue * 1.5;

The program memory usage jumps to 40-50% as shown in the picture.

Thanks in advance.

Picture ------ Upper image: low mem. Lower image: high mem.


Solution

  • The 16F18323 does not have a floating-point unit, meaning that it cannot natively perform a floating-point operations. As a result, the compiler must emulate floating-point operations in software, and subsequently must emit a lot of code for even a single floating-point operation.

    The first operation involves a constant expression and hence does not involve floating-point operations on the chip.

    For your specific example, you may consider an integer-based approach instead:

    red = blue + (blue / 2);
    

    or alternatively (if your compiler does not generate efficient code for division by powers of two):

    red = blue + (blue >> 1);
    

    Note that the result may differ slightly due to rounding. Additionally, note that shifting signed types (such as your int) is implementation-defined; the XC8 compiler defines a shift on a signed value as a sign-extending arithmetic shift, which is what we want.