Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
crc16.cpp
00001 #include "crc16.h" 00002 00003 /* 00004 CRC16 generation algorithm taken from J.G. Harston at 00005 http://mdfs.net/Info/Comp/Comms/CRC16.htm 00006 */ 00007 00008 // Refer to crc16.h for overall function details 00009 00010 #define poly 0x11021 // Define polynomial generating CRC tag 00011 00012 int crc16 (char* dataIn, int numberOfBytes) { 00013 if (numberOfBytes > 16) // Keep numberOfBytes under 16 00014 return 0; 00015 int i, j; 00016 int crc = 0; // Initialize CRC to zero 00017 00018 for (j = numberOfBytes ; j > 0; j--) { // Execute numberOfBytes times 00019 crc = crc ^ (*dataIn++ << 8); // Get byte and XOR with crc 00020 for (i = 0; i < 8; i++) { 00021 crc = crc << 1; // Rotate 00022 if (crc & 0x10000) // If bit 15 is set 00023 crc ^= poly; // XOR with polynomial 00024 } 00025 } 00026 return crc; // Return CRC tag 00027 } 00028 00029 void crc16_attach (char* dataIn, int numberOfBytes) { 00030 int crc = crc16(dataIn, numberOfBytes); // Generate CRC tag from first numberOfBytes elements of DataIn 00031 dataIn[numberOfBytes] = ((crc >> 8) & 0xFF); // Store 8 MSbits as the next element in dataIn 00032 dataIn[numberOfBytes + 1] = (crc & 0xFF); // Store the 8 LSbits is the last element in dataIn 00033 } 00034 00035 bool crc16_match (char* dataIn, int numberOfBytes) { 00036 int crcData = crc16(dataIn, numberOfBytes); // Generate CRC tag from the first numberOfBytes elements of dataIn 00037 int a,b; 00038 a = dataIn[numberOfBytes]; // Extract the last two 8 bit elements of dataIn as integers 00039 b = dataIn[numberOfBytes + 1]; 00040 int crcExpect = (a << 8) + b; // Recombine into a single 16 bit element 00041 if (crcData == crcExpect) // Compare the generated with the expected 00042 return true; // If they match, data is intact 00043 else 00044 return false; // Otherwise, data is not intact 00045 }
Generated on Thu Jul 14 2022 22:34:28 by
 1.7.2
 1.7.2