CRC16算法之一:CRC16-CCITT-FALSE算法的java实现

 

CRC16算法系列文章:

 

CRC16算法之一:CRC16-CCITT-FALSE算法的java实现

CRC16算法之二:CRC16-CCITT-XMODEM算法的java实现

CRC16算法之三:CRC16-CCITT-MODBUS算法的java实现

 

前言

 

JDK里包含了CRC32的算法,但是没有CRC16的,网上搜了一堆没有找到想要的,索性自己实现

注意:CRC16算法分为很多种,本篇文章中,只讲其中的一种:CRC16-CCITT-FALSE算法

CRC16算法系列之一:CRC16-CCITT-FALSE算法的java实现

功能

1、支持short类型

2、支持int类型

3、支持数组任意区域计算

实现

/**
 * crc16-ccitt-false加密工具
 * 
 * @author eguid
 *
 */
public class CRC16 {

	/**
	 * crc16-ccitt-false加/解密(四字节)
	 * 
	 * @param bytes
	 * @return
	 */
	public static int crc16(byte[] bytes) {
		return crc16(bytes, bytes.length);
	}

	/**
	 * crc16-ccitt-false加/解密(四字节)
	 * 
	 * @param bytes -字节数组
	 * @return
	 */
	public static int crc16(byte[] bytes, int len) {
		int crc = 0xFFFF;
		for (int j = 0; j < len; j++) {
			crc = ((crc >>> 8) | (crc << 8)) & 0xffff;
			crc ^= (bytes[j] & 0xff);// byte to int, trunc sign
			crc ^= ((crc & 0xff) >> 4);
			crc ^= (crc << 12) & 0xffff;
			crc ^= ((crc & 0xFF) << 5) & 0xffff;
		}
		crc &= 0xffff;
		return crc;
	}

	/**
	 * crc16-ccitt-false加/解密(四字节)
	 * 
	 * @param bytes
	 * @return
	 */
	public static int crc16(byte[] bytes, int start, int len) {
		int crc = 0xFFFF;
		for (; start < len; start++) {
			crc = ((crc >>> 8) | (crc << 8)) & 0xffff;
			crc ^= (bytes[start] & 0xff);// byte to int, trunc sign
			crc ^= ((crc & 0xff) >> 4);
			crc ^= (crc << 12) & 0xffff;
			crc ^= ((crc & 0xFF) << 5) & 0xffff;
		}
		crc &= 0xffff;
		return crc;
	}

	/**
	 * crc16-ccitt-false加/解密
	 * 
	 * @param bytes
	 *            -字节数组
	 * @return
	 */
	public static short crc16_short(byte[] bytes) {
		return crc16_short(bytes, 0, bytes.length);
	}

	/**
	 * crc16-ccitt-false加/解密(计算从0位置开始的len长度)
	 * 
	 * @param bytes
	 *            -字节数组
	 * @param len
	 *            -长度
	 * @return
	 */
	public static short crc16_short(byte[] bytes, int len) {
		return (short) crc16(bytes, len);
	}

	/**
	 * crc16-ccitt-false加/解密(两字节)
	 * 
	 * @param bytes
	 * @return
	 */
	public static short crc16_short(byte[] bytes, int start, int len) {
		return (short) crc16(bytes, start, len);
	}
}

 

 

 

 

 

 

 

 

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

eguid_1

感谢支持eguid原创技术文章

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值