和校驗、異或校驗、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