2021SC@SDUSC
串口数据类
private byte[] data = null;
private String sRecTime = "";
private String sComPort = "";
private boolean success = true;
public ComBean(String sPort, byte[] buffer, int size) {
sComPort = sPort;
data = new byte[size];
for (int i = 0; i < size; i++)
{
data[i] = buffer[i];
}
SimpleDateFormat sDateFormat = new SimpleDateFormat("hh:mm:ss");
sRecTime = sDateFormat.format(new java.util.Date());
}
使用for循环,将buffer中的数据依次赋值给data数组,使用SimpleDateFormat("hh:mm:ss")
得到hh:mm:ss形式的对象。
public class ComUtil {
static String tag = ComUtil.class.getSimpleName();
public static final int shortest_send_space = 600;
public static final int longest_out_time = 500;
public static final int read_space = 50;
}
shortest_send_space
定义了发送命令的最小时间间隔600ms
longest_out_time
定义了发送命令后,超时时间为500ms
read_space
定义了读取的时间间隔50ms
这两个类为前面提到的定时退出跳转界面,重回主界面提供了时间。
MyFunc 类
static public int isOdd(int num)
{
return num & 0x1;
}
判断奇数或偶数,位运算,最后一位是1则为奇数,为0是偶数
static public int HexToInt(String inHex)
{
return Integer.parseInt(inHex, 16);
}
Hex字符串转int
static public byte HexToByte(String inHex)
{
return (byte)Integer.parseInt(inHex,16);
}
Hex字符串转byte
static public String Byte2Hex(Byte inByte)
{
return String.format("%02x", inByte).toUpperCase();
}
1字节转2个Hex字符
static public String ByteArrToHex(byte[] inBytArr)
{
StringBuilder strBuilder=new StringBuilder();
int j=inBytArr.length;
for (int i = 0; i < j; i++)
{
strBuilder.append(Byte2Hex(inBytArr[i]));
strBuilder.append(" ");
}
return strBuilder.toString();
}
字节数组转转hex字符串
static public String ByteArrToHex(byte[] inBytArr,int offset,int byteCount)
{
StringBuilder strBuilder=new StringBuilder();
int j=byteCount;
for (int i = offset; i < j; i++)
{
strBuilder.append(Byte2Hex(inBytArr[i]));
}
return strBuilder.toString();
}
字节数组转转hex字符串,可选长度
static public byte[] HexToByteArr(String inHex)
{
int hexlen = inHex.length();
byte[] result;
if (isOdd(hexlen)==1)
{//奇数
hexlen++;
result = new byte[(hexlen/2)];
inHex="0"+inHex;
}else {//偶数
result = new byte[(hexlen/2)];
}
int j=0;
for (int i = 0; i < hexlen; i+=2)
{
result[j]=HexToByte(inHex.substring(i,i+2));
j++;
}
return result;
}
}
转hex字符串转字节数组,最终得到一个byte[]数组。
Java中byte用二进制表示占用8位,16进制的每个字符需要用4位二进制位来表示(23 + 22 + 21 + 20 = 15),所以我们使用两个相应的16进制字符就可以转换成一个byte。同理,每个byte转换成两个相应的16进制字符,即把byte的高4位和低4位分别转换成相应的16进制字符H和L,并组合起来得到byte转换到16进制字符串的结果new String(H) + new String(L)。byte用十六进制表示只占2位。这样就完成数据的转换。