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

Android 開發常用:byte 陣列與數值型別的轉換工具集

編輯:關於 Android 程式設計

處理 socket 通訊、檔案二進位內容或 JNI 資料時,byte 與 int / short / long 之間的轉換幾乎無可避免。Java 的 byte 是有符號的,直接轉型容易出錯,所以這裡把常用方法整理成一份工具類,順便把每個位操作的用意註解清楚。

/** 將單個 byte 轉為無符號的 int */
public static int unsignedByteToInt(byte b) {
    return (int) b & 0xFF;
}

/** 將單個 byte 轉為十六進位字串 */
public static String byteToHex(byte b) {
    int i = b & 0xFF;
    return Integer.toHexString(i);
}

/** 將 4 個 byte 組成 32 位元的無符號值 */
public static long unsigned4BytesToInt(byte[] buf, int pos) {
    int firstByte = 0;
    int secondByte = 0;
    int thirdByte = 0;
    int fourthByte = 0;
    int index = pos;
    firstByte = (0x000000FF & ((int) buf[index]));
    secondByte = (0x000000FF & ((int) buf[index + 1]));
    thirdByte = (0x000000FF & ((int) buf[index + 2]));
    fourthByte = (0x000000FF & ((int) buf[index + 3]));
    index = index + 4;
    return ((long) (firstByte << 24 | secondByte << 16
            | thirdByte << 8 | fourthByte)) & 0xFFFFFFFFL;
}

/** 將 16 位元 short 轉為長度 2 的 byte 陣列(大端序) */
public static byte[] shortToByteArray(short s) {
    byte[] targets = new byte[2];
    for (int i = 0; i < 2; i++) {
        int offset = (targets.length - 1 - i) * 8;
        targets[i] = (byte) ((s >>> offset) & 0xff);
    }
    return targets;
}

/** 32 位元整數轉 byte 陣列(小端序,最低位在前) */
public static byte[] int2byte(int res) {
    byte[] targets = new byte[4];
    targets[0] = (byte) (res & 0xff);        // 最低位
    targets[1] = (byte) ((res >> 8) & 0xff);  // 次低位
    targets[2] = (byte) ((res >> 16) & 0xff); // 次高位
    targets[3] = (byte) (res >>> 24);         // 最高位,無符號右移
    return targets;
}

/** 長度 2 的 byte 陣列轉 16 位元 int(小端序) */
public static int byte2int(byte[] res) {
    // res[0] 左移 24 位變成 0x??000000,再右移 8 位變成 0x00??0000
    int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00);
    return targets;
}

/** byte 陣列轉 short 陣列 */
public static short[] byteArray2ShortArray(byte[] data) {
    if (data == null) {
        return null;
    }
    short[] retVal = new short[data.length / 2];
    for (int i = 0; i < retVal.length; i++) {
        retVal[i] = (short) ((data[i * 2] & 0xff) | (data[i * 2 + 1] & 0xff) << 8);
    }
    return retVal;
}

/** short 陣列轉 byte 陣列 */
public static byte[] shortArray2ByteArray(short[] data) {
    byte[] retVal = new byte[data.length * 2];
    for (int i = 0; i < retVal.length; i++) {
        int mod = i % 2;
        if (mod == 0) {
            retVal[i] = (byte) (data[i / 2]);
        } else {
            retVal[i] = (byte) (data[i / 2] >> 8);
        }
    }
    return retVal;
}

/** 物件序列化為 byte 陣列 */
public static byte[] toByteArray(Object obj) {
    byte[] bytes = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(obj);
        oos.flush();
        bytes = bos.toByteArray();
        oos.close();
        bos.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return bytes;
}

/** byte 陣列反序列化為物件 */
public static Object toObject(byte[] bytes) {
    Object obj = null;
    try {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bis);
        obj = ois.readObject();
        ois.close();
        bis.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
    }
    return obj;
}

幾個容易出錯的地方

  • 有符號陷阱:Java 的 byte 範圍是 -128~127,轉 int 時一定要 & 0xFF 做遮罩,否則 0xFF 會變成 -1。
  • 位序要一致:上面範例裡 short、int 的轉換採用的是小端序(低位在前),而 shortToByteArray 是大端序。跨模組使用時務必確認對端採用哪一種,否則數值會完全錯位。
  • 用無符號右移 >>>:處理高位元組時要用 >>>,一般 >> 會保留符號位。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved