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

Android byte[] 與 short[]、int[]、long[] 互轉完整工具類解析

編輯:關於 Android 程式設計

在做 Android 底層開發時,只要碰到 Socket 通訊、藍牙/USB 數據幀解析、音訊 PCM 取樣,或者把結構化資料寫進二進位檔案,幾乎都繞不開同一件事:把 short、int、long 這些基本型別拆成位元組序列,或者反過來把一串位元組還原成數值。

這個過程看似簡單,真正的坑卻在「位元組序」上。同一個 short 值 0x1234,大端序(Big Endian)存成 12 34,小端序(Little Endian)則存成 34 12。如果送出的位元組序和對端約定不一致,收到的就是完全对不上的亂數。所以在動手寫轉換之前,先弄清楚自己在哪一端、對方又是哪一端。

一、先判斷當前裝置的位元組序

Java 提供了 ByteOrder.nativeOrder(),可以直接讀出執行環境的原生序。絕大多數 ARM 架構的 Android 裝置是小端序,但寫成判斷式永遠比寫死安全:

public boolean testCPU() {
    if (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN) {
        return true;   // 大端序
    } else {
        return false;  // 小端序
    }
}

二、完整工具類代碼

下面的 BytesTransUtil 把單值轉換與陣列批量轉換都封裝了起來。每個方法都帶一個 bBigEnding 參數,讓呼叫端自行決定位元組序;同時另外提供一組不帶參數的重載版本,預設採用裝置的原生序,日常使用更省事。

import java.nio.ByteOrder;

public class BytesTransUtil {

    private String TAG = "BytesTransUtil";
    private static BytesTransUtil instance = null;

    private BytesTransUtil() {
    }

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

    /** 判斷是否為大端序 */
    public boolean testCPU() {
        return ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN;
    }

    /* ============ 數值 -> 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;
    }

    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;
    }

    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[] -> 數值 ============ */

    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;
    }

    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;
    }

    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;
    }

    /* ============ 一層薄封裝:預設使用裝置原生序 ============ */

    public byte[] getBytes(int i)   { return getBytes(i, this.testCPU()); }
    public byte[] getBytes(short s) { return getBytes(s, this.testCPU()); }
    public byte[] getBytes(long l)  { return getBytes(l, this.testCPU()); }

    public int    getInt(byte[] buf)   { return getInt(buf, this.testCPU()); }
    public short  getShort(byte[] buf) { return getShort(buf, this.testCPU()); }
    public long   getLong(byte[] buf)  { return getLong(buf, this.testCPU()); }

    /* ============ 陣列批量轉換 ============ */

    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;
    }

    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;
    }

    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;
    }
}

三、驗證用的測試代碼

寫完工具類一定要跑一輪「轉出去再轉回來」的往返測試,確認數值沒有失真。下面以 int 陣列為例,short[]、long[] 的寫法完全同理:

public class main {

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

        int[] sTest = { 12345678, 87654321 };

        byte[] byteInt = bytesTransUtil.Ints2Bytes(sTest);
        int[] sTemp = bytesTransUtil.Bytes2Ints(byteInt);

        System.out.println("int[0] = " + sTemp[0] + "   int[1] = " + sTemp[1]);
    }
}

四、幾個實務上要注意的地方

位元組序務必對齊。工具類雖然能自動抓原生序,但跟外部裝置或伺服器對接時,兩端要明確約定,不要依賴「猜」。協定文件裡通常會寫清楚是 network byte order(大端)還是小端。

陣列長度必須是整數倍。Bytes2Shorts 這類方法用整數除法算出元素個數,若傳入的位元組數組長度不是 2、4、8 的倍數,多餘的尾巴會被靜默丟棄。正式專案裡建議先做一次長度校驗並拋出例外,比事後查資料好找多了。

注意符號擴展。這裡用 & 0x00ff 做遮罩,正是為了避免 byte 轉成 int 時的符號擴展把高位元填成 1。這個細節漏掉,負數就會全錯。

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