JAVA 의 CRC 검사 알고리즘
1587 단어 JAVA 구음 진경
byte 형 배열 을 입력 하여 두 요 소 를 만 드 는 byte 형 배열 (즉 16 비트)
public static byte[] makefcs(byte[] data)
{
int crc=0xFFFF;
byte[] buf = new byte[data.length];//
byte[] bup=new byte[2];
for (int i = 0; i < data.length; i++) {
buf[i] = data[i]; //
}
int len = buf.length;
for (int pos = 0; pos < len; pos++) {
if (buf[pos] < 0) {
crc ^= (int) buf[pos] + 256; //^ : , 0, 1
} else {
crc ^= (int) buf[pos];
}
for (int i = 8; i != 0; i--) {
if ((crc & 0x0001) != 0) {
crc >>= 1; //
crc ^= 0xA001;
} else
crc >>= 1;
}
}
String c = Integer.toHexString(crc);
if (c.length() == 4) {
c = c.substring(2, 4) + c.substring(0, 2);
} else if (c.length() == 3) {
c = "0" + c;
c = c.substring(2, 4) + c.substring(0, 2);
} else if (c.length() == 2) {
c = "0" + c.substring(1, 2) + "0" + c.substring(0, 1);
}
bup[0]=(byte)(Integer.parseInt(c.substring(0, 1), 16)+Integer.parseInt(c.substring(1,2), 16));
bup[1]=(byte)(Integer.parseInt(c.substring(2, 3), 16)+Integer.parseInt(c.substring(3,4), 16));
return bup;
}