package tools;
|
import java.math.BigInteger;
|
|
public class Jiaoyan {
|
|
/**获取校验码除去包头相加取反*/
|
public static byte[] check(byte[] byt) {
|
|
//字节数组转为16进制字符串/2后的长度
|
int size=BinaryToHexString2(byt).length()/2;
|
String[] hex=hex(BinaryToHexString2(byt));
|
|
//求和
|
int sum=0;
|
for(int i=0;i<size;i++) {
|
sum+=decodeHEX(hex[i]);
|
}
|
|
//取反转为16进制字符串
|
String hex16=Integer.toHexString(~sum);
|
|
//字符串的长度
|
int lenth=hex16.length();
|
|
byte[] jiaoyan=hexStringToByteArray(hex16.substring(lenth-4, lenth));
|
|
return jiaoyan;
|
|
}
|
|
|
/**获取校验码除去包头相加取反*/
|
public static String check2(String byt) {
|
|
//字节数组转为16进制字符串/2后的长度
|
int size=byt.length()/2;
|
String[] hex=hex(byt);
|
|
//求和
|
int sum=0;
|
for(int i=2;i<size-2;i++) {
|
sum+=decodeHEX(hex[i]);
|
}
|
|
//取反转为16进制字符串
|
String hex16=Integer.toHexString(~sum);
|
|
//字符串的长度
|
int lenth=hex16.length();
|
|
String jiaoyan=hex16.substring(lenth-4, lenth);
|
|
return jiaoyan.toUpperCase();
|
|
}
|
|
/**16进制转为10进制*/
|
public static int decodeHEX(String hexs){
|
BigInteger bigint=new BigInteger(hexs, 16);
|
int numb=bigint.intValue();
|
return numb;
|
|
}
|
|
/**将16进制字符串转为hex字符串数组2个字符串一个*/
|
public static String[] hex(String message) {
|
int size=message.length()/2;
|
String[] hex=new String[size];
|
for(int i=0;i<size;i++) {
|
hex[i]=message.substring(i*2, 2+i*2);
|
}
|
|
return hex;
|
}
|
|
|
/**将字节数组转换为16进制字符串无空格*/
|
public static String BinaryToHexString2(byte[] bytes) {
|
String hexStr = "0123456789ABCDEF";
|
String result = "";
|
String hex = "";
|
for (byte b : bytes) {
|
hex = String.valueOf(hexStr.charAt((b & 0xF0) >> 4));
|
hex += String.valueOf(hexStr.charAt(b & 0x0F));
|
result += hex + "";
|
}
|
return result;
|
}
|
|
|
/**
|
* 16进制表示的字符串转换为字节数组
|
*
|
* @param hexString 16进制表示的字符串
|
* @return byte[] 字节数组
|
*/
|
public static byte[] hexStringToByteArray(String hexString) {
|
hexString = hexString.replaceAll(" ", "");
|
int len = hexString.length();
|
byte[] bytes = new byte[len / 2];
|
for (int i = 0; i < len; i += 2) {
|
// 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个字节
|
bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
|
.digit(hexString.charAt(i+1), 16));
|
}
|
return bytes;
|
}
|
|
}
|