Advertisement
xladomaz

CRC8 implementation in C

Apr 15th, 2021
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdint.h>
  4. #include <stdbool.h>
  5. #include <string.h>
  6.  
  7. /*
  8. * 1 + x + x^3
  9. */
  10. #define POLYNOMIAL 0b101
  11. #define MAX_u8 0xFF
  12.  
  13. void test_crc();
  14. bool contains_in_array(uint8_t* arr, uint8_t size, uint8_t number);
  15.  
  16. uint8_t calc_crc(uint8_t* data, uint8_t size, uint8_t polynomial);
  17.  
  18. int main() {
  19. test_crc();
  20.  
  21. char str[512];
  22. printf("Enter text for calculate CRC8: ");
  23. gets(str);
  24. size_t str_len = strlen(str);
  25.  
  26. printf("Entered text: %s\n", str);
  27. printf("CRC8 of entered text: 0x%X\n", calc_crc((uint8_t*)str, str_len, POLYNOMIAL));
  28. }
  29.  
  30. void test_crc() {
  31. printf("Testing CRC for numbers in range [0; %u]\n", MAX_u8);
  32. uint8_t* crc = malloc(MAX_u8 + 1);
  33. uint8_t array_size = 0;
  34.  
  35. uint8_t collysion = 0;
  36. for (int i = 0; i <= MAX_u8; i++) {
  37. uint8_t current_crc = calc_crc(&(uint8_t)i, 1, POLYNOMIAL);
  38. if (contains_in_array(crc, array_size, current_crc)) {
  39. collysion++;
  40. }
  41. else {
  42. crc[array_size++] = current_crc;
  43. }
  44. }
  45.  
  46. free(crc);
  47.  
  48. printf("Amount collysions: %d\n", collysion);
  49. printf("Collysion rate: %d%%\n", (uint8_t)((100 * collysion) / MAX_u8));
  50. }
  51.  
  52. bool contains_in_array(uint8_t* arr, uint8_t size, uint8_t number) {
  53. for (uint8_t i = 0; i < size; i++)
  54. if (arr[i] == number)
  55. return true;
  56. return false;
  57. }
  58.  
  59. uint8_t calc_crc(uint8_t* data, uint8_t size, uint8_t polynomial) {
  60. uint8_t crc = 0x00;
  61. for (uint8_t i = 0; i < size; i++) {
  62. crc ^= data[i];
  63. for (uint8_t j = 0; j < 8; j++) {
  64. crc = (crc & 0x80) != 0 ? (crc << 1) ^ polynomial : crc << 1;
  65. }
  66. }
  67.  
  68. return crc;
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement