遇到通过wifi接受的数据,要通过转换成十六进制字符串,或者最后又是十进制数据。都是根据双方的协议来开发的。那么我发送过去的数据也需要,经过特殊转换成byte字节发过去,硬件那边收到不至于乱码的数据。
1、硬件调试发给android这边是十六进制数据
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;
}
那么要根据这些数据转换成十六进制的字符串,如果你直接转换成String字符串那肯定乱码了。因为硬件调试发给android这边是十六进制数据。
可以看出跟硬件发的是不是一样了。这里面不是十六进制Y,CS就用00填充了。
当然这些都是根据双方收发数据来解析,处理的。
2、android端发给硬件那边
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;
}
}
那么这样发过去就不会错误或者乱码。
很多初学者,特别是在物联网方面弄不清楚这个基本数据交流的转换。
public static String byte2HexString(byte[] bytes) {
String hex= "";
if (bytes != null) {
for (Byte b : bytes) {
hex += String.format("%02X", b.intValue() & 0xFF);
}
}
return hex;
}
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;
}
Integer.toHexString(nCtrl)