Java异或校验
今天要用到异或校验,折腾了半天,写下来留作备用。
功能是将一串16进制的数进行异或校验,输出校验和。
代码:
import java.util.Scanner;
/* * 亦或校验算法 */
public class Checksum_XOR {
@SuppressWarnings"resource")
public static void mainString[] args) {
// TODO Auto-generated method stub
whiletrue){
int i = 0,j = 0;
Scanner scanner = new ScannerSystem.in);
String in = scanner.nextLine);
int len = in.length);
short inb[] = new short[len];
fori=0;i<len;i++){
inb[i] = charToHexin.charAti)); //将String里的每一个char转换为Hex
}
fori =0;i<len;i++){ //将每两个Hex合并成一个byte
inb[j] = byte) inb[i]<<4)&0x00f0)|inb[i+1])&0x000f));
i++;
j++;
}
byte temp = 0x00; //校验值
fori = 0;i<len/2;i++){ //异或
temp ^= inb[i];
}
System.out.printf"%x", temp);
}
}
static short charToHexchar x){ //将单个char转换为Hex
short result = 0;
switchx){
case 'a':result=10;break;
case 'b':result=11;break;
case 'c':result=12;break;
case 'd':result=13;break;
case 'e':result=14;break;
case 'f':result=15;break;
case 'A':result=10;break;
case 'B':result=11;break;
case 'C':result=12;break;
case 'D':result=13;break;
case 'E':result=14;break;
case 'F':result=15;break;
default:result = short) Character.getNumericValuex);break;
}
return result;
}
}