Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 與單片機通訊常用資料轉換方法整理

編輯:Android 開發實例

前言

Android 與單片機通訊時,常需要處理 GBK 中文、十六進位字串、byte 陣列與不同進位。以下整理常用轉換。

1. 十六進位字串轉中文

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

2. 中文轉 GB2312 位元組

public static byte[] gbkToString(String str) throws Exception {
    return new String(str.getBytes("GBK"), "gb2312").getBytes("gb2312");
}

3. byte 陣列轉連續十六進位

例如 7e 80 11 20 可轉為 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. 每個位元組以空格分隔

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 陣列轉任意進位

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

6. 十六進位字串轉 byte 陣列

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();
    return (byte) (_b0 ^ _b1);
}

小結

這些方法涵蓋單片機常見的 ASCII、GBK、十六進位與進位轉換。實際使用時,建議加上例外處理與空值檢查,並依裝置端與單片機的編碼約定調整。

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