Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdint.h>
- #include <stdbool.h>
- #include <string.h>
- /*
- * 1 + x + x^3
- */
- #define POLYNOMIAL 0b101
- #define MAX_u8 0xFF
- void test_crc();
- bool contains_in_array(uint8_t* arr, uint8_t size, uint8_t number);
- uint8_t calc_crc(uint8_t* data, uint8_t size, uint8_t polynomial);
- int main() {
- test_crc();
- char str[512];
- printf("Enter text for calculate CRC8: ");
- gets(str);
- size_t str_len = strlen(str);
- printf("Entered text: %s\n", str);
- printf("CRC8 of entered text: 0x%X\n", calc_crc((uint8_t*)str, str_len, POLYNOMIAL));
- }
- void test_crc() {
- printf("Testing CRC for numbers in range [0; %u]\n", MAX_u8);
- uint8_t* crc = malloc(MAX_u8 + 1);
- uint8_t array_size = 0;
- uint8_t collysion = 0;
- for (int i = 0; i <= MAX_u8; i++) {
- uint8_t current_crc = calc_crc(&(uint8_t)i, 1, POLYNOMIAL);
- if (contains_in_array(crc, array_size, current_crc)) {
- collysion++;
- }
- else {
- crc[array_size++] = current_crc;
- }
- }
- free(crc);
- printf("Amount collysions: %d\n", collysion);
- printf("Collysion rate: %d%%\n", (uint8_t)((100 * collysion) / MAX_u8));
- }
- bool contains_in_array(uint8_t* arr, uint8_t size, uint8_t number) {
- for (uint8_t i = 0; i < size; i++)
- if (arr[i] == number)
- return true;
- return false;
- }
- uint8_t calc_crc(uint8_t* data, uint8_t size, uint8_t polynomial) {
- uint8_t crc = 0x00;
- for (uint8_t i = 0; i < size; i++) {
- crc ^= data[i];
- for (uint8_t j = 0; j < 8; j++) {
- crc = (crc & 0x80) != 0 ? (crc << 1) ^ polynomial : crc << 1;
- }
- }
- return crc;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement