package com.ld.igds.protocol.es.dlt645.util;
|
|
/**
|
* 工具类
|
*
|
* @author czt
|
*/
|
public class Dlt645Utils {
|
|
|
public static String MSG_START = "FEFEFEFE"; //起始符
|
public static String MSG_END = "16"; //结尾符
|
|
public static void main(String[] args) {
|
String s = makeCheck("6857141222000068110433333433");
|
System.out.println(s);
|
}
|
|
/**
|
* 将6个字节的地址域,每字节2位 BCD码,转换为12位10进制数
|
*/
|
public static String addrToString(String str) {
|
byte[] bytes = stringToBytes(str);
|
return String.format("%02x%02x%02x%02x%02x%02x", bytes[5], bytes[4], bytes[3], bytes[2], bytes[1], bytes[0]);
|
}
|
|
/**
|
* DLT645校验码
|
*/
|
public static String makeCheck(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类型转换成byte数组
|
*/
|
public static byte[] stringToBytes(String str) {
|
if (str == null || str.equals("")) {
|
return null;
|
}
|
byte[] bytes = new byte[str.length() / 2];
|
for (int i = 0; i < bytes.length; i++) {
|
String subStr = str.substring(i * 2, i * 2 + 2);
|
bytes[i] = (byte) Integer.parseInt(subStr, 16);
|
}
|
return bytes;
|
}
|
|
/**
|
* 解析返回的具体数据
|
*/
|
public static Double parseData(String dataStr) {
|
byte[] data = stringToBytes(dataStr);
|
// 每个字节-33H处理
|
for (int i = 0; i < data.length; i++) {
|
data[i] = (byte) (data[i] - 0x33);
|
}
|
StringBuilder str = new StringBuilder();
|
// BCD码转换成10进制
|
for (byte b : data) {
|
str.insert(0, String.format("%02x", b));
|
}
|
return Double.parseDouble(str.toString()) * 0.01;
|
}
|
|
}
|