package com.xxcg.platform.common.util;
/**
* 包 名 :com.xxcg.platform.common.util
* 文 件 名 : Test
* 描 述 : TODO
* 作 者 :
* 创建时间 :2019/5/9 0009 18:48
* 版 本 :1.0
*/
public class CRC16 {
//crc效验
public CRC16(){
}
/**
* crc16效验算法
* @param data
* @param length 长度
* @return
*/
public static int crc16(byte[] data,int length){
int ucI,ucJ;
int uiCrcValue =0xFFFF;
for ( ucI = 0; ucI < length; ucI ++) {
uiCrcValue = uiCrcValue ^ (data[ucI] & 0xff);
for(ucJ = 0; ucJ < 8; ucJ++){
if((uiCrcValue & 0x0001)==1){
uiCrcValue = (uiCrcValue >> 1) ^ 0x8408;
}else{
uiCrcValue = (uiCrcValue >> 1);
}
}
}
return uiCrcValue;
}
/**
* 效验和处理
* @param data
* @return
*/
public static int crc16(byte[] data){
int ucI,ucJ;
int uiCrcValue =0xFFFF;
for ( ucI = 0; ucI < data.length; ucI ++) {
uiCrcValue = uiCrcValue ^ (data[ucI] & 0xff);
for(ucJ = 0; ucJ < 8; ucJ++){
if((uiCrcValue & 0x0001)==1){
uiCrcValue = (uiCrcValue >> 1) ^ 0x8408;
}else{
uiCrcValue = (uiCrcValue >> 1);
}
}
}
return uiCrcValue;
}
public static byte[] int2ByteArray(int i){
byte[] result=new byte[4];
result[0]=(byte)((i >> 24)& 0xFF);
result[1]=(byte)((i >> 16)& 0xFF);
result[2]=(byte)((i >> 8)& 0xFF);
result[3]=(byte)(i & 0xFF);
return result;
}
/**
* 低位 crc16
* @param data
* @param length
* @return
*/
public static byte lsbCRC16(byte[] data,int length){
int c =CRC16.crc16(data,length);
byte[] bytes = CRC16.int2ByteArray(c);
return (byte) (bytes[3] & 0xff);
}
/**
* 获取crc两位。 低位在前,高位在后
* @param data
* @param length
* @return
*/
public static byte[] getLSBANDMSB(byte[] data,int length){
int c =CRC16.crc16(data,length);
byte[] bytes = CRC16.int2ByteArray(c);
byte[] bydata = new byte[2];
bydata[0]=bytes[3];
bydata[1]=bytes[2];
return bydata;
}
/**
* 低位 crc16
* @param data
* @param length
* @return
*/
public static byte msbCRC16(byte[] data,int length){
int c =CRC16.crc16(data,length);
byte[] bytes = CRC16.int2ByteArray(c);
return (byte) (bytes[2] & 0xff);
}
public static void main(String[] args) {
byte[] data = new byte[] { 0x05, 0x00, 0x40, 0x01, (byte) 0x99,0x3A};
byte c =CRC16.lsbCRC16(data,4);
System.out.println(c & 0xff);
}
}