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

Android 位元組與數值型別轉換:byte[] 與 short[]/int[]/long[] 的雙向處理

編輯:關於 Android 程式設計

在做Socket 通訊、音訊處理或檔案格式解析時,幾乎一定會遇到 byte 陣列與 short、int、long 之間的轉換問題。Java 的位元運算本身很直觀,但一旦牽涉到位元組序(Endianness),寫出來的程式碼就必須同時考慮大端與小端兩種情況,否則在不同 CPU 架構間搬移時就會出現數值錯亂。

為什麼要先判斷 CPU 的位元組序

同一個 short 數值 0x1234,在大端(Big Endian)機器上存放為 0x12 0x34,在小端(Little Endian)機器上則是 0x34 0x12。Java 的 ByteBuffer 預設使用大端,但 ByteOrder.nativeOrder() 可以取得目前平台的實際順序。若你的資料要與 C 語言寫的 native 層或外部裝置互通,就必须以對方約定的順序來編碼。

核心工具類

下面的 BytesTransUtil 以單例形式封裝了單值與陣列兩層轉換。單值方法都接受一個 bBigEnding 參數,讓呼叫端自行決定位元組序;另外一組不帶該參數的重載版本則自動採用系統原生順序。

public class BytesTransUtil {

    private static BytesTransUtil instance = null;

    private BytesTransUtil() { }

    public static BytesTransUtil getInstance() {
        if (instance == null) {
            instance = new BytesTransUtil();
        }
        return instance;
    }

    /** 回傳 true 代表目前平台為大端序 */
    public boolean testCPU() {
        return ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN;
    }

    /** short → 2 個 byte */
    public byte[] getBytes(short s, boolean bBigEnding) {
        byte[] buf = new byte[2];
        if (bBigEnding) {
            for (int i = buf.length - 1; i >= 0; i--) {
                buf[i] = (byte) (s & 0x00ff);
                s >>= 8;
            }
        } else {
            for (int i = 0; i < buf.length; i++) {
                buf[i] = (byte) (s & 0x00ff);
                s >>= 8;
            }
        }
        return buf;
    }

    /** int → 4 個 byte */
    public byte[] getBytes(int s, boolean bBigEnding) {
        byte[] buf = new byte[4];
        if (bBigEnding) {
            for (int i = buf.length - 1; i >= 0; i--) {
                buf[i] = (byte) (s & 0x000000ff);
                s >>= 8;
            }
        } else {
            for (int i = 0; i < buf.length; i++) {
                buf[i] = (byte) (s & 0x000000ff);
                s >>= 8;
            }
        }
        return buf;
    }

    /** long → 8 個 byte */
    public byte[] getBytes(long s, boolean bBigEnding) {
        byte[] buf = new byte[8];
        if (bBigEnding) {
            for (int i = buf.length - 1; i >= 0; i--) {
                buf[i] = (byte) (s & 0x00000000000000ff);
                s >>= 8;
            }
        } else {
            for (int i = 0; i < buf.length; i++) {
                buf[i] = (byte) (s & 0x00000000000000ff);
                s >>= 8;
            }
        }
        return buf;
    }

    /** byte[] → short,長度不可超過 2 */
    public short getShort(byte[] buf, boolean bBigEnding) {
        if (buf == null) {
            throw new IllegalArgumentException("byte array is null!");
        }
        if (buf.length > 2) {
            throw new IllegalArgumentException("byte array size > 2 !");
        }
        short r = 0;
        if (bBigEnding) {
            for (int i = 0; i < buf.length; i++) {
                r <<= 8;
                r |= (buf[i] & 0x00ff);
            }
        } else {
            for (int i = buf.length - 1; i >= 0; i--) {
                r <<= 8;
                r |= (buf[i] & 0x00ff);
            }
        }
        return r;
    }

    /** byte[] → int,長度不可超過 4 */
    public int getInt(byte[] buf, boolean bBigEnding) {
        if (buf == null) {
            throw new IllegalArgumentException("byte array is null!");
        }
        if (buf.length > 4) {
            throw new IllegalArgumentException("byte array size > 4 !");
        }
        int r = 0;
        if (bBigEnding) {
            for (int i = 0; i < buf.length; i++) {
                r <<= 8;
                r |= (buf[i] & 0x000000ff);
            }
        } else {
            for (int i = buf.length - 1; i >= 0; i--) {
                r <<= 8;
                r |= (buf[i] & 0x000000ff);
            }
        }
        return r;
    }

    /** byte[] → long,長度不可超過 8 */
    public long getLong(byte[] buf, boolean bBigEnding) {
        if (buf == null) {
            throw new IllegalArgumentException("byte array is null!");
        }
        if (buf.length > 8) {
            throw new IllegalArgumentException("byte array size > 8 !");
        }
        long r = 0;
        if (bBigEnding) {
            for (int i = 0; i < buf.length; i++) {
                r <<= 8;
                r |= (buf[i] & 0x00000000000000ff);
            }
        } else {
            for (int i = buf.length - 1; i >= 0; i--) {
                r <<= 8;
                r |= (buf[i] & 0x00000000000000ff);
            }
        }
        return r;
    }
}

陣列層的批次轉換

實務上更常面對的是整組資料,例如一段 PCM 音訊就是 short 陣列,而從檔案讀進來的是 byte 陣列。做法是固定「每 N 個 byte 組成一個元素」的規則,反覆切分並轉換:

    /** short[] → byte[],每個 short 佔 2 個 byte */
    public byte[] Shorts2Bytes(short[] s) {
        byte bLength = 2;
        byte[] buf = new byte[s.length * bLength];
        for (int iLoop = 0; iLoop < s.length; iLoop++) {
            byte[] temp = getBytes(s[iLoop]);
            for (int jLoop = 0; jLoop < bLength; jLoop++) {
                buf[iLoop * bLength + jLoop] = temp[jLoop];
            }
        }
        return buf;
    }

    /** byte[] → short[] */
    public short[] Bytes2Shorts(byte[] buf) {
        byte bLength = 2;
        short[] s = new short[buf.length / bLength];
        for (int iLoop = 0; iLoop < s.length; iLoop++) {
            byte[] temp = new byte[bLength];
            for (int jLoop = 0; jLoop < bLength; jLoop++) {
                temp[jLoop] = buf[iLoop * bLength + jLoop];
            }
            s[iLoop] = getShort(temp);
        }
        return s;
    }

    /** int[] 與 long[] 的轉換結構完全相同,只要把 bLength 換成 4 或 8 */
    public int[] Bytes2Ints(byte[] buf) {
        byte bLength = 4;
        int[] s = new int[buf.length / bLength];
        for (int iLoop = 0; iLoop < s.length; iLoop++) {
            byte[] temp = new byte[bLength];
            for (int jLoop = 0; jLoop < bLength; jLoop++) {
                temp[jLoop] = buf[iLoop * bLength + jLoop];
            }
            s[iLoop] = getInt(temp);
        }
        return s;
    }

    public byte[] Ints2Bytes(int[] s) {
        byte bLength = 4;
        byte[] buf = new byte[s.length * bLength];
        for (int iLoop = 0; iLoop < s.length; iLoop++) {
            byte[] temp = getBytes(s[iLoop]);
            for (int jLoop = 0; jLoop < bLength; jLoop++) {
                buf[iLoop * bLength + jLoop] = temp[jLoop];
            }
        }
        return buf;
    }

    public long[] Bytes2Longs(byte[] buf) {
        byte bLength = 8;
        long[] s = new long[buf.length / bLength];
        for (int iLoop = 0; iLoop < s.length; iLoop++) {
            byte[] temp = new byte[bLength];
            for (int jLoop = 0; jLoop < bLength; jLoop++) {
                temp[jLoop] = buf[iLoop * bLength + jLoop];
            }
            s[iLoop] = getLong(temp);
        }
        return s;
    }

    public byte[] Longs2Bytes(long[] s) {
        byte bLength = 8;
        byte[] buf = new byte[s.length * bLength];
        for (int iLoop = 0; iLoop < s.length; iLoop++) {
            byte[] temp = getBytes(s[iLoop]);
            for (int jLoop = 0; jLoop < bLength; jLoop++) {
                buf[iLoop * bLength + jLoop] = temp[jLoop];
            }
        }
        return buf;
    }

驗證:一次來回轉換

public class Main {
    public static void main(String[] args) {
        BytesTransUtil util = BytesTransUtil.getInstance();

        int[] source = { 12345678, 87654321 };
        byte[] bytes = util.Ints2Bytes(source);
        int[] result = util.Bytes2Ints(bytes);

        System.out.println("值[0] = " + result[0] + ",值[1] = " + result[1]);
    }
}

輸出應與輸入完全一致。若不一致,第一個要懷疑的就是編碼與解碼時用了不同的位元組序。

幾個實作上的提醒

  • >>= 對負數會做正負號擴展,但因為每次都立刻用 & 0xff 取低 8 位元再轉成 byte,結果仍然正確;若改用 >>>= 也無妨,語意更清楚。
  • getShort 回傳的 short 若原本數值超過 32767,會呈現負數,這是 Java short 的先天限制,必要時改用 int 承載。
  • 若效能是重點,Android 上可直接用 ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getShort(),比手寫迴圈更簡潔,也少了邊界檢查的遺漏風險。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved