喘JAVA糞?CRC16丕刮鷹
扮寂:2011-02-23
1?Design
2?Code
import java.io.IOException;
public class CRC16Checker {
private static int[] index = new int[] { 16, 15, 2, 0 };
private static int[] getBinary(String text) {
StringBuffer num = new StringBuffer();
String s; char ch;
for (int i = 0; i < text.length(); i++) { // Change each char to binary code.
s = Integer.toBinaryString(text.charAt(i));
// If the code is less than 8 bit, make it as 8 bit.
for (int j = 8 - s.length(); j > 0; j--) num.append(0);
num.append(s);
}
int len = num.length();
int[] code = new int[len];
for (int i = 0; i < len; i++) // Change each 0/1 char to int.
code[i] = Character.getNumericValue(num.charAt(i));
return code;
}
private static String toHex(int[] num) {
StringBuffer hex = new StringBuffer(num.length / 4);
char[] ch = new char[4];
for (int i = 0; i < num.length;) {
// Change each 0/1 int to char.
ch[0] = Character.forDigit(num[i++], 2);
ch[1] = Character.forDigit(num[i++], 2);
ch[2] = Character.forDigit(num[i++], 2);
ch[3] = Character.forDigit(num[i++], 2);
// Change each 4-bit-code to hex number.
hex.append(Integer.toHexString(Integer.parseInt(String.valueOf(ch), 2)));
}
return hex.toString();
}
// CRC codes main process
public static int[] makeCRCCodes(int[] sourceCodes, int[] multinomial) {
// The lenght of CRC code is N bits longer than source code. The codes
// from 0 to sourceLength are same as the source. N bits after source
// are the CRC codes. N is decided by the multinomial.
// CRC鷹方怏悳海葎圻鷹海紗貧丕刮鷹鷹海。方怏念何贋慧圻鷹。丕刮鷹贋慧壓方怏
// 恷朔議N了。丕刮鷹海業畳協噐伏撹謹?塀方怏0了崔貧議圷殆。
int sourceLength = sourceCodes.length;
int codesLength = sourceLength + multinomial[0];
int[] crcCodes = new int[codesLength];
// Copy source code from 0 to sourceLength. 申唄圻鷹。
System.arraycopy(sourceCodes, 0, crcCodes, 0, sourceLength);
int
|