Blame view

C5/xpadprotocal/src/main/java/com/sunvote/utils/Crc16.java 2.37 KB
fac86401   孙向锦   初始化C5 Vote
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
  package com.sunvote.utils;
  
  public class Crc16 {
  
  	private static int[] crc_ta= { //CRC余式表
  			0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,
  			0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,
  	};
  
  
  	//标准Crc16效验
  	public static short crc16(byte[] data,int len)//uchar *ptr, uchar len
  	{ 	short crc;
  		byte da;
  		int i=4;
  
  		crc=0;
  		while(len--!=0)
  		{
  			//da=Crc>>12; /* 暂存CRC的高四位 */
  			da=   (byte)(crc>>>12) ; /* 暂存CRC的高四位 */
  
  			// Crc<<=4; /* CRC左移4位,相当于取CRC的低12位)*/
  			crc<<=4; /* CRC左移4位,相当于取CRC的低12位)*/
  
  			//  Crc^=crc_ta[da^(*ptr/16)]; /* CRC的高4位和本字节的前半字节相加后查表计算CRC,  然后加上上一次CRC的余数 */
  			crc^=crc_ta[(da^ (data[i]>>>4)) & 0xf]; /* CRC的高4位和本字节的前半字节相加后查表计算CRC,  然后加上上一次CRC的余数 */
  
  			//da=Crc>>12; /* 暂存CRC的高4位 */
  			da= (byte)(crc>>>12); /* 暂存CRC的高4位 */
  
  			// Crc<<=4; /* CRC左移4位, 相当于CRC的低12位) */
  			crc<<=4; /* CRC左移4位, 相当于CRC的低12位) */
  
  			// Crc^=crc_ta[da^ (*ptr&0x0f)];
  			crc^=crc_ta[ (da ^ data[i])&0x0f]; /* CRC的高4位和本字节的后半字节相加后查表计算CRC
                                        然后再加上上一次CRC的余数 */
  
  			// ptr++;
  			i++;
  		}
  		return (crc);
  	}
  
  	public static boolean crc16Check(byte[] data){
  		int crcValue = Crc16
  				.getUnsignedShort(Crc16.crc16(data, data.length - 4 - 2));
  		int originCrcValue = 0;
  		originCrcValue |= (data[data.length - 2] & 0xff) << 8;
  		originCrcValue |= data[data.length - 1] & 0xff;
  		return crcValue == originCrcValue ;
  	}
  
  	public static int getUnsignedByte (byte data){      //将data字节型数据转换为0~255 (0xFF 即BYTE)。
  		return data&0x0FF;
  	}
  
  	public static int getUnsignedShort (short data){      //将data字节型数据转换为0~255 (0xFF 即BYTE)。
  		return data&0x0FFFF;
  	}
  
  	private static void printDataBuf(byte[] buf,int length, String flag){
  		String tmpStr = new String() ;
  		for(int i=0;i<length;i++){
  			tmpStr += String.format("%x ", buf[i]);
  		}
  		System.out.println(flag+  ":" + tmpStr);
  	}
  
  	public static boolean checkPack(byte[] buf){
  		if(buf.length>4 && getUnsignedByte(buf[0])==0xF5 && getUnsignedByte(buf[1])==0xAA && getUnsignedByte(buf[2])==0xAA ){
  			return true;
  		}
  		return false;
  	}
  
  
  }