Android 发送十六进制byte的问题

lishi_1991 2014-10-14 07:05:22
我需要在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端做什么修改呢?
...全文
316 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
lishi_1991 2014-10-15
  • 打赏
  • 举报
回复
谢谢 最后我重写了jni发送接口,改为发送byte[]在jni里将jbyteArray转为jbyte;再发送就不出错了
svenwang 2014-10-14
  • 打赏
  • 举报
回复
可以用这个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));
}

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧