Quick table lookup

General discussion on mikroC PRO for PIC.
Post Reply
Author
Message
john p
Posts: 40
Joined: 19 Sep 2016 18:54

Quick table lookup

#1 Post by john p » 02 Feb 2022 20:38

Maybe this will help somebody. I'm setting up a communication network using packets which end with a CRC (cyclic redundancy code) to run on a PIC16F18345. Learning how to generate the CRC, I found that there are two ways to do it as new characters get added to the packet. One way is with a series of 8 tests on each bit of the new data byte, each one causing an XOR operation on the present value of the old CRC to create a new CRC. The other method is faster, because it involves a single XOR and then a lookup in a 256-byte table, so with plenty of program space to spare, I decided to use that method.

I tried making a 256-byte global const array, and telling the program to simply grab a byte out of it as needed. That worked, but when I looked at the list file I thought the way the compiler set it up was clumsy. Then I noticed that when my array was placed into the executable file, each byte of the array was expanded so that the upper byte (upper 6 bits, actually) made it into a RETLW operation. The compiler did that, but then just read the low byte as data and never used the code. So I thought maybe I could replace the 256 bytes of data with 256 RETLW lines in a function, and actually use the RETLW. In fact it was quite easy, and will undoubtedly be fast in operation. It looks like this. An initial function takes the call for an update of the CRC (new data is in incoming.input):

Code: Select all

void crc_bits(void)
{
    WREG = incoming.input ^ incoming.checksum;
    crc_lookup();                         // Call is made with result of XOR operation in W
    incoming.checksum = WREG;      // Call returns with new CRC in W
}
You don't need to use the operations involving the W register in C code, if you're willing to add a line of assembly code each time. Then the CRC lookup is entirely in assembly, but you certainly don't need to know much about it to make it work:

Code: Select all

void crc_lookup(void)
{
   asm {
      BRW
      RETLW 0
      RETLW 0X5E
      RETLW 0XBC
   ... etc etc
}
What the BRW operation does is jump ahead according to the current value of W. So it jumps to the appropriate RETLW line, loads W with the value it finds there, and returns to the calling function. Pretty simple!

User avatar
filip
mikroElektronika team
Posts: 11874
Joined: 25 Jan 2008 09:56

Re: Quick table lookup

#2 Post by filip » 03 Feb 2022 11:33

Hi,

Thank you for his code, it seems very interesting! :)

Regards,
Filip.

Post Reply

Return to “mikroC PRO for PIC General”