mbed I/F binding for mruby

Dependents:   mruby_mbed_web mirb_mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers crc.c Source File

crc.c

00001 /*
00002 ** crc.c - calculate CRC
00003 **
00004 ** See Copyright Notice in mruby.h
00005 */
00006 
00007 #include <limits.h>
00008 #include <stdint.h>
00009 #include <stddef.h>
00010 
00011 /* Calculate CRC (CRC-16-CCITT)
00012 **
00013 **  0000_0000_0000_0000_0000_0000_0000_0000
00014 **          ^|------- CRC -------|- work --|
00015 **        carry
00016 */
00017 #define  CRC_16_CCITT       0x11021ul        /* x^16+x^12+x^5+1 */
00018 #define  CRC_XOR_PATTERN    (CRC_16_CCITT << 8)
00019 #define  CRC_CARRY_BIT      (0x01000000)
00020 
00021 uint16_t
00022 calc_crc_16_ccitt(const uint8_t *src, size_t nbytes, uint16_t crc)
00023 {
00024   size_t ibyte;
00025   uint32_t ibit;
00026   uint32_t crcwk = crc << 8;
00027 
00028   for (ibyte = 0; ibyte < nbytes; ibyte++) {
00029     crcwk |= *src++;
00030     for (ibit = 0; ibit < CHAR_BIT; ibit++) {
00031       crcwk <<= 1;
00032       if (crcwk & CRC_CARRY_BIT) {
00033         crcwk ^= CRC_XOR_PATTERN;
00034       }
00035     }
00036   }
00037   return (uint16_t)(crcwk >> 8);
00038 }
00039 
00040