Search code examples
cpicmultiplication

2digit multiplication on 8bit system


I'm looking for a way to multiply 2 numbers together (both 2 digits) I'm programming in C and using a PIC18F4455 chip, as well as CCS compiler.
Here is the issue:

code:

#include<18F4455.h>
#fuses HS,NOWDT,NOPROTECT,NOLVP
#device ICD=TRUE
#use delay(clock=5000000)
#include<lcd.c>  //LCD display source code
#include<kbd_xy.c> //keypad source code
void main(){
    char k;
    //
    //code to retrive keypad input and store in a and b values
    // 
    unsigned long c;
    unsigned int a=99;
    unsigned int b=1;
    while(b<99)
    {
        c=a*b;
        printf(lcd_putc,"%Ld",c);
        delay_ms(1000);
        lcd_putc('\f');
    }
}

The issue is that the numbers stored in c cannot exceed 256 due to the chip being 8bit. so 991 gives 099, 992 gives 198, but 993 gives 41, note 993=297 which is 256+41 and so on...

I'm looking for a better way to get the true results, they are going to be displayed via LCD so if i end up with 4 variables each housing a digit that's O.K. by me. if when i do 99*3 i get variables like c1=7 c2=9 c3=2 and c4=0 thats awesome


Solution

  • I solved my own issue. It seems that by default any declared int in the CCS compiler is an int8.
    SO the remedy was quite simple:

    #include<18F4455.h>
    #fuses HS,NOWDT,NOPROTECT,NOLVP
    #device ICD=TRUE
    #use delay(clock=5000000)
    #include<lcd.c>  //LCD display source code
    #include<kbd_xy.c> //keypad source code
    void main(){
        char k;
        //
        //code to retrive keypad input and store in a and b values
        // 
        int16 c;
        int16 a=99;
        int16 b=1;
        while(b<99)
        {
            c=a*b;
            printf(lcd_putc,"%Ld",c);
            delay_ms(1000);
            lcd_putc('\f');
        }
    }