接上篇TCP
本文主要是TCP连接中所用到的一些转换函数:
public class DataUtil {
//buffer转string
public static String decodeKey(ByteBuffer bytes) {
Charset charset = Charset.forName("utf-8");
return charset.decode(bytes).toString();
}
//buffer转byte[]
public static byte[] decodeValue(ByteBuffer bytes) {
int len = bytes.limit() - bytes.position();
byte[] bytes1 = new byte[bytes.limit()];
if (bytes.hasArray()){
System.arraycopy(bytes.array(),0,bytes1,0,bytes.limit());
return bytes1;
}
return null;
}
//string转buffer
public static ByteBuffer encodeKey(String key) {
try {
return ByteBuffer.wrap(key.getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return ByteBuffer.wrap(key.getBytes());
}
//byte[]转 buffer
public static ByteBuffer encodeValue(byte[] value) {
ByteBuffer byteBuffer = ByteBuffer.allocate(value.length);
byteBuffer.put(value);
byteBuffer.flip();
return byteBuffer;
}
/**
* 将字节数组转换成十六进制的字符串
*
* @return
*/
public static String BinaryToHexString(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;
}
/**
* 将十六进制的字符串转换成字节数组
*
* @param hexString
* @return
*/
public static byte[] hexStrToBinaryStr(String hexString) {
if (hexString.isEmpty()) {
return null;
}
hexString = hexString.replaceAll(" ", "");
int len = hexString.length();
int index = 0;
byte[] bytes = new byte[len / 2];
while (index < len) {
String sub = hexString.substring(index, index + 2);
bytes[index/2] = (byte)Integer.parseInt(sub,16);
index += 2;
}
return bytes;
}
/**
* 16进制浮点转10进制
* @return
*/
public static double modbusFloat(String s) {
byte[] bits = hexStrToBinaryStr(s);
double rtn = 0;
int flag = 1;
if (bits.length == 4) {
int E = bits[0] & 0x80;
if (E > 0) {
flag = -1;
}
E = ((bits[0] & 0x7F) << 1) + ((bits[1] & 0x80) >> 7);
double M10 = 0.0;
for (int i = 1; i <= 7; i++) {
M10 += (bits[1] >> (7 - i) & 0x01) * Math.pow(2, -1 * i);
}
for (int i = 1; i <= 8; i++) {
M10 += (bits[2] >> (8 - i) & 0x01) * Math.pow(2, -1 * (i + 7));
}
for (int i = 1; i <= 8; i++) {
M10 += (bits[3] >> (8 - i) & 0x01) * Math.pow(2, -1 * (i + 15));
}
String data = "" + (1.0 + M10);
double dVal = Double.parseDouble(data);
rtn = flag * dVal * (Math.pow(2, E - 127));
}
return rtn;
}
}