要求:1)以命令行形式运行:check_sum infile
其中check_sum为程序名,infile为输入数据文件名。
2)输出:数据文件的效验和
附:效验和(checksum)
原理:把要发送的数据看成二进制整数序列,并计算他们的和。若数据字节长度为奇数,则在数据尾部补一个字节的0以凑成偶数。
例子:16位效验和计算,下图表明一个小的字符串的16位效验和的计算。
为了计算效验和,发送计算机把每对字符当成16位整数处理并计算效验和。如果效验和大于16位,那么把进位一起加到最后的效验和中。
public class CRC {/**
* CRC-CCITT(Kermit)验证模式
* @param str
* @return
*/
public String CRC_CCITT_Kermit(String str) {
int j, b, rrrc, c, i
String tmpBalance
int k
rrrc = 0
tmpBalance = str
int tmpInt, CharInt
String tmpChar, tmpStr
tmpStr = ""
int High
int Low
for (j = 1j <= 3j++) {
if (Character.isDigit(tmpBalance.charAt(2 * j - 2))) {
High = Integer.parseInt(tmpBalance.charAt(2 * j - 2) + "")
} else {
High = 0
}
if (Character.isDigit(tmpBalance.charAt(2 * j - 1))) {
Low = Integer.parseInt(tmpBalance.charAt(2 * j - 1) + "")
} else {
Low = 0
}
High = (High &0xff) <<4
High = High | Low
k = High
for (i = 1i <= 8i++) {
c = rrrc &1
rrrc = rrrc >>1
if ((k &1) != 0) {
rrrc = rrrc | 0x8000
}
if (c != 0) {
rrrc = rrrc ^ 0x8408
}
k = k >>1
}
}
for (i = 1i <= 16i++) {
c = rrrc &1
rrrc = rrrc >>1
if (c != 0) {
rrrc = rrrc ^ 0x8408
}
}
c = rrrc >>8
b = rrrc <<8
rrrc = c | b
tmpInt = rrrc
tmpStr = ""
for (i = 1i <= 4i++) {
tmpChar = ""
CharInt = tmpInt % 16
if (CharInt >9) {
switch (CharInt) {
case 10:
tmpChar = "A"
break
case 11:
tmpChar = "B"
break
case 12:
tmpChar = "C"
break
case 13:
tmpChar = "D"
break
case 14:
tmpChar = "E"
break
case 15:
tmpChar = "F"
break
}
} else {
tmpChar = Integer.toString(CharInt)
}
tmpInt = tmpInt / 16
tmpStr = tmpChar + tmpStr
}
System.out.println("tmpStr:" + tmpStr)
return tmpStr
}
/**
* CRC-CCITT(XModem)
* CRC-CCITT(0xFFFF)
* CRC-CCITT(0x1D0F)
* 校验模式
* @param flag<XModem(flag=1) 0xFFFF(flag=2) 0x1D0F(flag=3)>
* @param str
* @return
*/
public String CRC_CCITT( int flag,String str) {
int crc = 0x00 // initial value
int polynomial = 0x1021
byte[] bytes=str.getBytes()
switch(flag){
case 1:
crc=0x00
break
case 2:
crc=0xFFFF
break
case 3:
crc=0x1D0F
break
}
for (int index = 0 index<bytes.lengthindex++) {
byte b = bytes[index]
for (int i = 0i <8i++) {
boolean bit = ((b >>(7-i) &1) == 1)
boolean c15 = ((crc >>15&1) == 1)
crc <<= 1
if (c15 ^ bit) crc ^= polynomial
}
}
crc &= 0xffff
str = Integer.toHexString(crc)
return str
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)