Advertisement
glank

crc16.c

Jun 19th, 2017
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.85 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdint.h>
  4.  
  5. static uint16_t *crc16_table()
  6. {
  7.   static uint16_t crc_table[256];
  8.   static _Bool generate_table = 1;
  9.   if (generate_table) {
  10.     const uint16_t p = 0xA001;
  11.     for (int i = 0; i < 256; ++i) {
  12.       uint16_t crc = 0;
  13.       uint16_t c = i;
  14.       for (int j = 0; j < 8; ++j) {
  15.         crc = (crc >> 1) ^ (((crc ^ c) & 1) ? p : 0);
  16.         c >>= 1;
  17.       }
  18.       crc_table[i] = crc;
  19.     }
  20.     generate_table = 0;
  21.   }
  22.   return crc_table;
  23. }
  24.  
  25. uint16_t crc16(void *data, size_t size)
  26. {
  27.   uint16_t *crc_table = crc16_table();
  28.   uint8_t *data_u8 = data;
  29.   uint16_t crc = 0x0000;
  30.   for (size_t i = 0; i < size; ++i)
  31.     crc = (crc >> 8) ^ crc_table[(crc ^ data_u8[i]) & 0x00FF];
  32.   return crc;
  33. }
  34.  
  35. int main()
  36. {
  37.   char s[256];
  38.   gets(s);
  39.   printf("0x%04X\n", crc16(s, strlen(s)));
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement