package com.modbus.data;
|
public class ComFn {
|
public static String bytesToHexString(byte[] src, int len){
|
StringBuilder stringBuilder = new StringBuilder("");
|
if (src == null || len <= 0) {
|
return null;
|
}
|
for (int i = 0; i < len; i++) {
|
int v = src[i] & 0xFF;
|
String hv = Integer.toHexString(v).toUpperCase();
|
if (hv.length() < 2) {
|
stringBuilder.append(0);
|
}
|
stringBuilder.append(hv + " ");
|
}
|
return stringBuilder.toString();
|
}
|
|
/**
|
* 16进制字符串 转换为对应的 byte数组
|
*/
|
public static byte[] hex2Bytes(String hex) {
|
if (hex == null || hex.length() == 0) {
|
return null;
|
}
|
|
char[] hexChars = hex.toCharArray();
|
byte[] bytes = new byte[hexChars.length / 2]; // 如果 hex 中的字符不是偶数个, 则忽略最后一个
|
|
for (int i = 0; i < bytes.length; i++) {
|
bytes[i] = (byte) Integer.parseInt("" + hexChars[i * 2] + hexChars[i * 2 + 1], 16);
|
}
|
|
return bytes;
|
}
|
}
|