Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdint.h>
- static uint16_t *crc16_table()
- {
- static uint16_t crc_table[256];
- static _Bool generate_table = 1;
- if (generate_table) {
- const uint16_t p = 0xA001;
- for (int i = 0; i < 256; ++i) {
- uint16_t crc = 0;
- uint16_t c = i;
- for (int j = 0; j < 8; ++j) {
- crc = (crc >> 1) ^ (((crc ^ c) & 1) ? p : 0);
- c >>= 1;
- }
- crc_table[i] = crc;
- }
- generate_table = 0;
- }
- return crc_table;
- }
- uint16_t crc16(void *data, size_t size)
- {
- uint16_t *crc_table = crc16_table();
- uint8_t *data_u8 = data;
- uint16_t crc = 0x0000;
- for (size_t i = 0; i < size; ++i)
- crc = (crc >> 8) ^ crc_table[(crc ^ data_u8[i]) & 0x00FF];
- return crc;
- }
- int main()
- {
- char s[256];
- gets(s);
- printf("0x%04X\n", crc16(s, strlen(s)));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement