CRC16校验
C++中的代码如下:传入字节(byte)数组引用和数组长度
unsigned short CTcpClient::Crc16(const char *pBuf, unsigned short nLen) { BYTE i; unsigned short crc = 0; while (nLen--) { for (i = 0x80; i != 0; i >>= 1) { if ((crc&0x8000) != 0) { crc <<= 1; crc ^= 0x1021; } else { crc <<= 1; } if ((*pBuf&i) != 0) { crc ^= 0x1021; } } pBuf++; } return crc; }
java代码如下,传入byte数组
public static int getCrc16 ( byte[] b ) { int crc, i; crc = 0; int count = b.length; for(int c =0;c<count;c++) { crc = (int) (crc ^ (int) b[c] << 8); for(i = 0; i < 8; i++) { if ((crc & 0x8000) != 0) crc = (int) (crc << 1 ^ 0x1021); else crc = (int) (crc << 1); } } return (int) (crc & 0xFFFF); }