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

 

CRC16算法系列文章:

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

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

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

 

前言

CRC16算法有很多种,本篇文章会介绍其中的CRC16-CCITT-XMODEM算法

 

功能

实现CRC16-CCITT-XMODEM算法

支持int、short类型

支持选择数组区域计算

实现

package cc.eguid.crc16;

/**
 * crc16多项式算法
 * @author eguid
 *
 */
public class CRC16 {
	
   /**
     * CRC16-XMODEM算法(四字节)
     * @param bytes
     * @return
     */
    public static int crc16_ccitt_xmodem(byte[] bytes) {
        return crc16_ccitt_xmodem(bytes,0,bytes.length);
    }
    
    /**
     * CRC16-XMODEM算法(四字节)
     * @param bytes 
     * @param offset
     * @param count
     * @return
     */
    public static int crc16_ccitt_xmodem(byte[] bytes,int offset,int count) {
        int crc = 0x0000; // initial value
        int polynomial = 0x1021; // poly value
        for (int index = offset; index < count; index++) {
            byte b = bytes[index];
            for (int i = 0; i < 8; i++) {
                boolean bit = ((b >> (7 - i) & 1) == 1);
                boolean c15 = ((crc >> 15 & 1) == 1);
                crc <<= 1;
                if (c15 ^ bit)
                    crc ^= polynomial;
            }
        }
        crc &= 0xffff;
        return crc;
    }
    
    /**
     * CRC16-XMODEM算法(两字节)
     * @param bytes 
     * @param offset
     * @param count
     * @return
     */
    public static short crc16_ccitt_xmodem_short(byte[] bytes,int offset,int count) {
    	return (short)crc16_ccitt_xmodem(bytes,offset,count);
    }
    /**
     * CRC16-XMODEM算法(两字节)
     * @param bytes 
     * @param offset
     * @param count
     * @return
     */
    public static short crc16_ccitt_xmodem_short(byte[] bytes) {
    	return crc16_ccitt_xmodem_short(bytes,0,bytes.length);
    }
    
}

---end---

 

 

 

 

 

 

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

eguid_1

感谢支持eguid原创技术文章

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

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

打赏作者

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

抵扣说明:

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

余额充值