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

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

編輯:關於 Android 開發

數據轉換為何重要

在 Android 與單片機通信過程中,經常需要在字符串、字節數組、十六進制表示以及不同編碼格式之間轉換。例如單片機通常直接處理字節流,而 Android 層更常使用字符串或日誌形式展示數據。

GBK 字符串與字節數組互轉

當通信協議使用 GB2312 或 GBK 編碼時,可以將十六進制字符串還原為字節數組,再按照指定編碼解析成字符串。例如兩個十六進制字符可以合成一個字節,多個字節再按 GBK 解析為中文。

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);
    }
    return new String(bytes, "GBK");
}

字節數組轉十六進制字符串

在調試通信數據時,將 byte 數組轉成十六進制字符串非常方便查看。這種方式常用於日誌輸出,因為原始字節往往不可直接閱讀。

public static String bytesToHexString(byte[] src) {
    StringBuilder builder = new StringBuilder();
    if (src == null || src.length == 0) {
        return null;
    }
    for (byte value : src) {
        int v = value & 0xFF;
        String hv = Integer.toHexString(v);
        if (hv.length() < 2) {
            builder.append('0');
        }
        builder.append(hv);
    }
    return builder.toString();
}

如果希望每個字節之間用空格分隔,也可以在格式化時加入分隔符,使日誌更易讀。

十六進制字符串轉 byte 數組

與上述過程相反,有時需要把字符串形式的十六進制數據還原成 byte 數組,以便發送給單片機或寫入設備。

public static byte[] hexStringToBytes(String src) {
    byte[] ret = new byte[src.length() / 2];
    for (int i = 0; i < ret.length; i++) {
        ret[i] = (byte) Integer.parseInt(src.substring(i * 2, i * 2 + 2), 16);
    }
    return ret;
}

不同進制之間的轉換

有時需要將 byte 數組整體解釋為一個大整數,再輸出為十進制、十六進制或其他進制。這類場景可以借助 BigInteger 完成。

public static String bytesToAllHex(byte[] bytes, int radix) {
    return new BigInteger(1, bytes).toString(radix);
}

其中參數 1 表示將數據作為正數處理,radix 表示目標進制。

小結

在 Android 與單片機通信中,常見轉換包括 GBK 編碼轉換、十六進制字符串與 byte 數組互轉、字節數據日誌化輸出,以及不同進制之間的數值轉換。掌握這些方法,可以顯著提升通信調試與協議解析效率。

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