Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 與單片機通信常用數據轉換方法總結

編輯:關於 Android 程式設計

在做 Android 與單片機(MCU)通信的項目時,經常會遇到各種數據格式的相互轉換,比如十六進制、GB2312 中文字符、字節數組之間的互轉。本文把這些高頻用到的轉換方法整理出來,方便大家查閱使用。

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 字節數組

例如把「胡蘿卜」轉成 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[]{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[]{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. 將字節數組轉為指定進制

可轉為 8、10、16 等任意進制,例如 byte[]{0x11, 0x20} 轉成 4384(10 進制),其中 radix 代表進制:

 public static String bytesToAllHex(byte[] bytes, int radix) { return new BigInteger(1, bytes).toString(radix);// 這裡的1代表正數 } 

6. 將十六進制字符串轉為字節數組

例如把 7e20 轉成 new byte[]{0x7e, 0x20}:

 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 與單片機通信中常用的數據轉換方法整理,後續會繼續補充相關內容。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved