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

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 与单片机通信的资料整理,后续继续补充相关资料谢谢大家对本站的支持!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值