62,620
社区成员
发帖
与我相关
我的任务
分享public class CRC {
//according file calculate the 16-bit CRC of a string using a byte-oriented tableless algorithm
public short CalCRC(byte[] s, int len, short crcval) {
int CRC = crcval;
int c;
int q;
int j = 0;
for(;len > 0;len--){
c = s[j++];
q = (CRC^c) & 017;
CRC = (CRC >> 4) ^ (q* 010201);
q = (CRC ^(c >> 4)) & 017;
CRC = (CRC >> 4) ^ (q * 010201);
}
return (short)CRC;
}
public static short do_crc(byte[] message){
int len = message.length;
int i, j;
short crc_reg;
crc_reg = (short)( (message[0] << 8) + message[1]);
for (i = 0; i < len; i++){
if (i < len - 2)
for (j = 0; j <= 7; j++)
{
if ((short)crc_reg < 0)
crc_reg = (short)(((crc_reg << 1) + (message[i + 2] >> (7 - i))) ^ 0x1021);
else
crc_reg = (short)((crc_reg << 1) + (message[i + 2] >> (7 - i)));
}
else
for (j = 0; j <= 7; j++)
{
if ((short)crc_reg < 0)
crc_reg = (short)((crc_reg << 1) ^ 0x1021);
else
crc_reg <<= 1;
}
}
return crc_reg;
}public static int Crc_ccitt_good(byte[] sz) {
int poly = 0x1021;
short xor_flag;
short good_crc = (short) 0xffff;
int len = sz.length;
for (int len1 = 0; len1 < len; len1++) {// 数据总长度
short i, v;
v = 0x80;
for (i = 0; i < 8; i++) { // 处理完8位数据
if ((good_crc & 0x8000) > 0) // 判断CRC寄存器最高位是否为1
xor_flag = 1;
else
xor_flag = 0;
good_crc = (short) (good_crc << 1); // CRC寄存器左移一位,
// 把要处理的数据移入CRC寄存器
if ((sz[len1] & v) > 0) // 判断要移入CRC寄存器的数据位是否为1
good_crc = (short) (good_crc + 1);// 为1则CRC寄存器+1,为0则不加
if (xor_flag > 0) // 移出的数据为1,则CRC寄存器与多项式相异或
good_crc = (short) (good_crc ^ poly);
v = (short) (v >> 1); // 指向移入CRC寄存器的数据位
}
}
for (int j = 0; j < 16; j++) {// 这下面的程序是干吗用的?按说上面那段程序得到的
// good_crc就是CRC校验和吧?不知我理解的对不?
if ((good_crc & 0x8000) > 0)
xor_flag = 1;
else
xor_flag = 0;
good_crc = (short) (good_crc << 1);
if (xor_flag > 0)
good_crc = (short) (good_crc ^ poly);
}
return good_crc;
} public static short cal_crc(byte[] ptr) {
char i;
short crc = 0;
int len = ptr.length;
for (int index = 0; index < len; index++) {
for (i = 0x80; i != 0; i /= 2) {
if ((crc & 0x8000) != 0) {/* 余式CRC乘以2再求CRC */
crc *= 2;
crc ^= 0x1021;
} else
crc *= 2;
if ((ptr[index] & i) != 0)
crc ^= 0x1021; /* 再加上本位的CRC */
}
}
return crc;
} public static int java( byte[] bytes) {
int crc = 0xFFFF; // initial value
int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)
// byte[] testBytes = "123456789".getBytes("ASCII");
for (int index = 0 ; index< bytes.length; 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;
// System.out.println("CRC16-CCITT = " + Integer.toHexString(crc));
return crc;
} public static int CRC_CCITT1(byte d[]){
byte b = 0;
short crc = (short)0xffff;
int i, j;
int len = d.length;
for(i=0; i<len; i++){
for(j=0; j<8; j++){
b = (byte)(((d[i]<<j)&0x80) ^ ((crc&0x8000)>>8));
crc<<=1;
if(b!=0)
crc^=0x1021;
}
}
crc = (short)~crc;
return crc&0xffff;
}