Ask Question

Name:
Title:
Your Question:

Answer Question

Name:
Your Answer:
User Submitted Source Code!


Description:
  sdfdf
Language: C/C++
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>

typedef unsigned char u8;
typedef unsigned short u16;

static u8   crc8_table[256];
#define DI  0x07

void init_crc8();
u8 crc8(u8 *bufferPtr, u16 bufferSize);

#define MODE_INPUT

int main(void)
{
     #ifndef MODE_INPUT
          u8 buff[] = "SB,001,1534567890,EB,";
     #else
          u8 buff[256];
     #endif
     
     init_crc8();

     for(;;)
     {
          u16 size = sizeof(buff) - 1;
          #ifdef MODE_INPUT
               printf("\n-------------------------------------------------------------------------------\nBuffer a ser feito CRC: ");
               scanf("%s", &buff[0]);
               for(int i = 0; i < sizeof(buff); i++)
               {
                    if(buff[i] == 0)
                    {
                         size = i;
                         break;
                    }
               }
          #endif
          
          printf("nPacote montado: %s%03d", buff, crc8(&buff[0], size));
          
          #ifndef MODE_INPUT
               break;
          #endif
     }
     
     getch();
}

void init_crc8()
{
    u16 i,j;
    u8 crc;
                                                                              
    for (i = 0; i < 256; i++) 
    {
        crc = i;
        for (j = 0; j < 8; j++)
        {
            crc = (crc << 1) ^ ((crc & 0x80) ? DI : 0);
        }
        crc8_table[i] = crc & 0xFF;
    }
}

u8 crc8(u8 *bufferPtr, u16 bufferSize)
{
    u8 prevCrc = 0xFF;
    
    for(; bufferSize; bufferSize--)
    {
        prevCrc = crc8_table[(prevCrc) ^ (*bufferPtr++)];
    }
    
    return prevCrc;
}


          
          
Comments: