import java.text.SimpleDateFormat;
import java.util.Calendar;
class Tools {
/**
* vggbmmm 校验和算法
*
* @src 校验字符串首地址
* @sizes 总字节数
* @return 一个字节的校验和
*/
public static char checkSum(Byte[] rc_data) {
int sum = 0;
char ret = 0;
if (rc_data != null) {
for (int i = 0; i < rc_data.length; i++) {
sum += (char) rc_data[i].byteValue();
}
}
ret = (char) (sum & 0xff);
return ret;
}
//多态
public static char checkSum(byte[] rc_data) {
int sum = 0;
char ret = 0;
if (rc_data != null) {
for (int i = 0; i < rc_data.length; i++) {
sum += (char) rc_data[i];
}
}
ret = (char) (sum & 0xff);
return ret;
}
private final static char[] hexArray = "0123456789abcdef".toCharArray();
// 字节数组转字符串 效率高
public static String byteArrToHex(byte... bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
// 字节数据转字符串 通用,效率低
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
// modbus CRC16 校验
public static String getCRC(byte[] bytes) {
int CRC = 0x0000ffff;
int POLYNOMIAL = 0x0000a001;
int i, j;
for (i = 0; i < bytes.length; i++) {
CRC ^= ((int) bytes[i] & 0x000000ff);
for (j = 0; j < 8; j++) {
if ((CRC & 0x00000001) != 0) {
CRC >>= 1;
CRC ^= POLYNOMIAL;
} else {
CRC >>= 1;
}
}
}
CRC = ((CRC & 0xFF00) >> 8) | ((CRC & 0x00FF) << 8);// 高低位转换
// 补全4位
return String.format("%04x", CRC);
}
// 16进制字符串转字节数组
public static byte[] hexStringToByte(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
/**
* @功能: BCD码转为10进制串(阿拉伯数据)
* @参数: BCD码
* @结果: 10进制串
*/
public static String bcd2Str(byte[] bytes) {
StringBuffer temp = new StringBuffer(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
temp.append((byte) ((bytes[i] & 0xf0) >>> 4));
temp.append((byte) (bytes[i] & 0x0f));
}
return temp.toString().substring(0, 1).equalsIgnoreCase("0") ? temp
.toString().substring(1) : temp.toString();
}
//byte 数组与 int 的相互转换
public static int byteArrayToInt(byte[] b) {
return b[3] & 0xFF |
(b[2] & 0xFF) << 8 |
(b[1] & 0xFF) << 16 |
(b[0] & 0xFF) << 24;
}
private static int toByte(char c) {
byte b = (byte) "0123456789abcdef".indexOf(c);
return b;
}
}