Alexandre Lemay
/
APP4_FunTimes
first
Diff: CRC.cpp
- Revision:
- 6:ac7c0ccf9b5d
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/CRC.cpp Tue Oct 24 02:33:50 2017 +0000 @@ -0,0 +1,50 @@ +#include "CRC.h" + +const unsigned short CRCPOLYNOM = 0x8005; + +// The last two bytes of data corresponds to the remainder. If they are of 0,0, this function will return the remainder to put into them. +// If the two last bytes contains the crc received, the return should be of 0 +int crc16Remainder(std::vector<unsigned char> data, unsigned short generator) +{ + // shift generator + unsigned int polynom = generator << 16; + + if (data.empty()) + { + return -1; + } + + unsigned int remainder = data[0] << 24 | data[1] << 16; + + for (int i = 2; i < data.size(); i++) + { + remainder = remainder | data[i] << 8; + for (int j = 0; j < 8; j++) + { + // if msb is 1, shift and xor + if (remainder >> 31 ==1) + { + remainder = (remainder << 1) ^ polynom; + } + else + { + remainder = remainder << 1; + } + } + } + // Calculates remainder of last 16 bits + for (int i = 0; i < 16; i++) + { + // if msb is 1, shift and xor + if (remainder >> 31 == 1) + { + remainder = (remainder << 1) ^ polynom; + } + else + { + remainder = remainder << 1; + } + } + return remainder >> 16; + +}