遇到通过wifi接受的数据,要通过转换成十六进制字符串,或者最后又是十进制数据。都是根据双方的协议来开发的。那么我发送过去的数据也需要,经过特殊转换成byte字节发过去,硬件那边收到不至于乱码的数据。
1、硬件调试发给android这边是十六进制数据
原始数据:
68 38 38 68 A 72 78 55 34 12 43 23 01 07 Y 00 00 00 0C 13 78 56 34 12 0C 3B 78 34 12 0C 26 78 56 34 12 0B 59 45 23 00 02 FD 17 00 CS 16
android读到数据是byte字节数组
DataInputStream dis = new DataInputStream(new
BufferedInputStream(socket.getInputStream()));
byte readBuffer[] = new byte[64];
int count = 0;
try {
count = dis.read(readBuffer);
} catch (IOException e) {
continue;
}
readBuffer收到数据是这样的:
104, 56, 56, 104, 0, 114, 120, 85, 52, 18, 67, 35, 1, 7, 0, 0, 0, 0, 12, 19, 120, 86, 52, 18, 12, 59, 120, 52, 18, 12, 38, 120, 86, 52, 18, 11, 89, 69, 35, 0, 2, -3, 23, 0, 0, 22
那么要根据这些数据转换成十六进制的字符串,如果你直接转换成String字符串那肯定乱码了。因为硬件调试发给android这边是十六进制数据。
readBuffer字节数组转后数据十六进制是这样的:
68 , 38 , 38 , 68 , 00 , 72 , 78 , 55 , 34 , 12 , 43 , 23 , 01 , 07 , 00 , 00 , 00 , 00 , 0C , 13 , 78 , 56 , 34 , 12 , 0C , 3B , 78 , 34 , 12 , 0C , 26 , 78 , 56 , 34 , 12 , 0B , 59 , 45 , 23 , 00 , 02 , FD , 17 , 00 , 00 , 16
可以看出跟硬件发的是不是一样了。这里面不是十六进制Y,CS就用00填充了。
当然这些都是根据双方收发数据来解析,处理的。
2、android端发给硬件那边
android的原始数据是这个的:
68 04 04 68 35 FD 50 00 A0 16,
也是十六进制的字符串
需要做的就是十六进制的字符串转换成byte数组
private String mstrRestartSend = "FE FE 68 04 04 68 53 FD 50 00 A0 16";
private byte[] mRestart = null;
mRestart = StringUtil.HexCommandtoByte(mstrRestartSend.getBytes());
public class StringUtil {
// 十六进制的字符串转换成byte数组
public static byte[] HexCommandtoByte(byte[] data) {
if (data == null) {
return null;
}
int nLength = data.length;
String strTemString = new String(data, 0, nLength);
String[] strings = strTemString.split(" ");
nLength = strings.length;
data = new byte[nLength];
for (int i = 0; i < nLength; i++) {
if (strings[i].length() != 2) {
data[i] = 00;
continue;
}
try {
data[i] = (byte)Integer.parseInt(strings[i], 16);
} catch (Exception e) {
data[i] = 00;
continue;
}
}
return data;
}
}
那么这样发过去就不会错误或者乱码。
很多初学者,特别是在物联网方面弄不清楚这个基本数据交流的转换。
byte转16进制字符串
public static String byte2HexString(byte[] bytes) {
String hex= "";
if (bytes != null) {
for (Byte b : bytes) {
hex += String.format("%02X", b.intValue() & 0xFF);
}
}
return hex;
}
16进制字符串转byte
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
try {
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
} catch (Exception e) {
//Log.d("", "Argument(s) for hexStringToByteArray(String s)"+ "was not a hex string");
}
return data;
}
10进制数转16进制数
Integer.toHexString(nCtrl)