和校验、异或校验、crc循环余校验


不多逼逼,直接上代码~~~

 

和校验

/**
* 和校验
* @param data 十六进制字符串
* @return
*/
public static String makeChecksum(String data) {
if (data == null || data.equals("")) {
return "";
}
int total = 0;
int len = data.length();
int num = 0;
while (num < len) {
String s = data.substring(num, num + 2);
total += Integer.parseInt(s, 16);
num = num + 2;
}
/**
* 用256求余最大是255,即16进制的FF
*/
int mod = total % 256;
String hex = Integer.toHexString(mod);
len = hex.length();
// 如果不够校验位的长度,补0,这里用的是两位校验
if (len < 2) {
hex = "0" + hex;
}
return hex.toUpperCase();
}

异或校验

/***
* 异或校验
* String para 十六进制字符串
* @return
*/

public static String checkcode_0007(String para){
String[] dateArr = new String[para.length()/2];
for(int i = 0,k = 0;k<para.length()/2;i+=2,k++){
dateArr[k] = para.substring(i,i+2);
}
String code = "";
for (int i = 0; i < dateArr.length-1; i++) {
if(i == 0){
code = xorHex(dateArr[i], dateArr[i+1]);
}else{
code = xorHex(code, dateArr[i+1]);
}
}
return code;
}

/**
*
* @param a 十六进制字节
* @param b 十六进制字节
* @return
*/
public static String xorHex(String a, String b) {
char[] chars = new char[a.length()];
for (int i = 0; i < chars.length; i++) {
chars[i] = toHex(fromHex(a.charAt(i)) ^ fromHex(b.charAt(i)));
}
return new String(chars);
}

private static int fromHex(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
throw new IllegalArgumentException();
}

private static char toHex(int nybble) {
if (nybble < 0 || nybble > 15) {
throw new IllegalArgumentException();
}
return "0123456789ABCDEF".charAt(nybble);
}

crc循环

使用方法: String crc = getBufHexStr(getSendBuf(""));
public static final String HEXES = "0123456789ABCDEF";
public static String getBufHexStr(byte [] raw){
if(raw == null){
return null;
}
final StringBuffer hex = new StringBuffer(2*raw.length);
for (final byte b : raw) {
hex.append(HEXES.charAt((b&0xf0)>>4)).append(HEXES.charAt((b&0x0f)));
}
return hex.toString();
}

public static byte[] getSendBuf(String toSend) {
byte[] bb = HexString2Buf(toSend);
crcCheck crc16 = new crcCheck();
crc16.update(bb, bb.length - 2);
int ri = crc16.getValue();
bb[bb.length - 1] = (byte) (0xff & ri);
bb[bb.length - 2] = (byte) ((0xff00 & ri) >> 8);
return bb;
}
private static byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode("0x" + new String(new byte[]{src0})).byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[]{src1})).byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
}

private static byte[] HexString2Buf(String src) {
int len = src.length();
byte[] ret = new byte[len / 2 + 2];
byte[] tmp = src.getBytes();
for (int i = 0; i < len; i += 2) {
ret[i / 2] = uniteBytes(tmp[i], tmp[i + 1]);
}
return ret;
}
均测试有效 ~~~





免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM