java版本CRC16

xiaoxiao2021-02-27  437

因为项目需要CRC16的校验,因此在博客上记录一下这个,貌似在网上挺难找的, /** * CRC16相关计算 * CRC16多项式:1021,初值:0000 */ public class CRC16 { public static short calCRC16(byte[] datas) { int crc = 0; for (int index = 0; index < datas.length; index++) { crc = update((short) crc, datas[index]); } crc = update((short) crc, (byte) 0); crc = update((short) crc, (byte) 0); return (short) (crc & (short) 0xffff); } public static short calRCR16(byte[] datas, int start) { int crc = 0; for (int index = start; index < datas.length; index++) { crc = update((short) crc, datas[index]); } crc = update((short) crc, (byte) 0); crc = update((short) crc, (byte) 0); return (short) (crc & (short) 0xffff); } public static short update(int crc, byte b) { int in = b & 0xff | 0x100; do { crc <<= 1; in <<= 1; if ((in & 0x100) > 0) { ++crc; } if ((crc & 0x10000) > 0) { crc ^= 0x1021; } } while ((in & 0x10000) <= 0); return (short) (crc & 0xffff); } }
转载请注明原文地址: https://www.6miu.com/read-3367.html

最新回复(0)