我需要在Android上把一串十六进制字符串通过3G网络发给pc做处理
发送的jni接口是发送string类型,而我得到的是string类型十六进制的字符串 所以我发送时候做了以下处理
byte[] send_to_pc_buf = new byte[100]; String ab ="0012234567EA5E7D45BFFA"; int j = 0; for(int i=0;i<ab.length();i=i+2){ send_to_pc_buf[j] = (byte) Integer.parseInt(ab.substring(i,i+2) ,16); j++; } send_to_pc_str = new String(send_to_pc_buf);
将得到的str调用jni接口发送 在发送端发现收到的数据有些问题
收到的数据:
查阅资料 Android byte型范围在0~127之间 所以大于127的数据都出错了,因为pc端必须接收的是16进制数据所以我需要修改Android发送程序,那我该怎么做呢
还有Android段会发送大量的0x00数据但是在pc端接收到的都是c0 80这是为什么呢 需要Android端做什么修改呢? 解决方案1
可以用这个decodeToString函数转换。
public int hexToInt(byte b) throws Exception {
if (b >= '0' && b <= '9') {
return (int)b - '0';
}
if (b >= 'a' && b <= 'f') {
return (int)b + 10 - 'a';
}
if (b >= 'A' && b <= 'F') {
return (int)b + 10 - 'A';
}
throw new Exception("invalid hex");
}
public byte[] decodeToBytes(String hexString) {
byte[] hex = hexString.getBytes();
if ((hex.length % 2) != 0) {
return null;
}
byte[] ret = new byte[hex.length / 2];
int j = 0;
int i = 0;
try {
while (i < hex.length) {
byte hi = hex[i++];
byte lo = hex[i++];
ret[j++] = (byte)((hexToInt(hi) << 4) | hexToInt(lo));
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return ret;
}
public String decodeToString(String hexString) {
return new String(decodeToBytes(hexString));
}