当前位置: 移动技术网 > IT编程>移动开发>Android > Android与单片机通信常用数据转换方法总结

Android与单片机通信常用数据转换方法总结

2019年07月24日  | 移动技术网IT编程  | 我要评论

征稿,山西邦泰网络营销,138高清影视

android与单片机通信常用数据转换方法

  1.  将gb2312转化为中文,如bafac2dcb2b7→胡萝卜,两个字节合成一个文字

public static string stringtogbk(string string) throws exception { 
  byte[] bytes = new byte[string.length() / 2]; 
  for (int j = 0; j < bytes.length; j++) { 
    byte high = byte.parsebyte(string.substring(j * 2, j * 2 + 1), 16); 
    byte low = byte.parsebyte(string.substring(j * 2 + 1, j * 2 + 2), 
        16); 
    bytes[j] = (byte) (high << 4 | low); 
  } 
  string result = new string(bytes, "gbk"); 
  return result; 
} 

  2.将中文转化为gb2312,并且结果以byte[]形式返回,如胡萝卜→new byte[]{ba  fa c2 dc b2 b7},一个字被分为两个字节

public static byte[] gbktostring(string str) throws exception { 
  return new string(str.getbytes("gbk"), "gb2312").getbytes("gb2312"); 
} 

  3.将十六进制的byte[]原封不动的转化为string,如byte[]{0x7e,0x80,0x11,0x20}→7e801120,可用于log打印

public static string bytestohexstring(byte[] src) { 
  stringbuilder stringbuilder = new stringbuilder(""); 
  if (src == null || src.length <= 0) { 
    return null; 
  } 
  for (int i = 0; i < src.length; i++) { 
    int v = src[i] & 0xff; 
    string hv = integer.tohexstring(v); 
    if (hv.length() < 2) { 
      stringbuilder.append(0); 
    } 
    stringbuilder.append(hv); 
  } 
  return stringbuilder.tostring(); 
} 

  4.将十六进制的byte[]原封不动的转化为string,并且每个byte之间用空格分开,如byte[]{0x7e,0x80,0x11,0x20}→7e 80 11 20,,可用于log打印

public static stringbuilder byte2hexstr(byte[] data) { 
 
  if (data != null && data.length > 0) { 
    stringbuilder stringbuilder = new stringbuilder(data.length); 
    for (byte bytechar : data) { 
      stringbuilder.append(string.format("%02x ", bytechar)); 
    } 
    return stringbuilder; 
  } 
  return null; 
} 

  5.将byte[]数组转化为8、10、16等各种进制,例如byte[0x11,0x20]→4384,约等于1120(16进制)→4384,radix代表进制

public static string bytestoallhex(byte[] bytes, int radix) { 
  return new biginteger(1, bytes).tostring(radix);// 这里的1代表正数 
} 

  6.将string的十六进制原封不动转化为byte的十六进制,例如7e20→new byte[]{0x7e,x20}

public static byte[] hexstring2bytes(string src) { 
  byte[] ret = new byte[src.length() / 2]; 
  byte[] tmp = src.getbytes(); 
  for (int i = 0; i < tmp.length / 2; i++) { 
    ret[i] = unitebytes(tmp[i * 2], tmp[i * 2 + 1]); 
  } 
  return ret; 
} 

public static byte unitebytes(byte src0, byte src1) { 
  byte _b0 = byte.decode("0x" + new string(new byte[] { src0 })) 
      .bytevalue(); 
  _b0 = (byte) (_b0 << 4); 
  byte _b1 = byte.decode("0x" + new string(new byte[] { src1 })) 
      .bytevalue(); 
  byte ret = (byte) (_b0 ^ _b1); 
  return ret; 
} 

以上就是对android 与单片机通信的资料整理,后续继续补充相关资料谢谢大家对本站的支持!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网