首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java int 與 long 轉 byte 陣列及反向轉換工具類實作

     編輯:Java 相關知識

應用場景

網絡通訊、二進制協議、文件存儲、數據庫 Blob 字段等場景,需將基本型別序列化為位元組陣列(大端序/網絡序),避免 String 轉換的空間與效能開銷。

核心工具類實作

public final class ByteOrderUtils {
    private ByteOrderUtils() {} // 工具類禁止實例化

    /** int → byte[4] (Big-Endian) */
    public static byte[] int2byte(int value) {
        byte[] bytes = new byte[4];
        bytes[3] = (byte) (value & 0xFF);
        bytes[2] = (byte) ((value >>> 8) & 0xFF);
        bytes[1] = (byte) ((value >>> 16) & 0xFF);
        bytes[0] = (byte) ((value >>> 24) & 0xFF); // 無符號右移
        return bytes;
    }

    /** byte[4] → int (Big-Endian) */
    public static int byteArrayToInt(byte[] bytes) {
        if (bytes == null || bytes.length < 4) throw new IllegalArgumentException("需要 4 字節");
        int v0 = (bytes[0] & 0xFF) << 24;
        int v1 = (bytes[1] & 0xFF) << 16;
        int v2 = (bytes[2] & 0xFF) << 8;
        int v3 = (bytes[3] & 0xFF);
        return v0 | v1 | v2 | v3;
    }

    /** long → byte[8] (Big-Endian) */
    public static byte[] long2byte(long value) {
        byte[] bytes = new byte[8];
        for (int i = 0; i < 8; i++) {
            int offset = 64 - (i + 1) * 8;
            bytes[i] = (byte) ((value >>> offset) & 0xFF);
        }
        return bytes;
    }

    /** byte[8] → long (Big-Endian) */
    public static long byteArrayToLong(byte[] bytes) {
        if (bytes == null || bytes.length < 8) throw new IllegalArgumentException("需要 8 字節");
        long val = 0;
        for (int i = 0; i < 8; i++) {
            val = (val << 8) | (bytes[i] & 0xFF);
        }
        return val;
    }
}

關鍵技術點解析

操作作用
& 0xFF將 byte 視為無符號 0~255,防止 Java 自動符號擴展(byte → int 時高位補 1)
>>>> (無符號右移)確保高位補 0,而非符號位複製
| (位或)合併各字節,避免符號位干擾
大端序高位字節存低地址,符合網絡傳輸標準 (RFC 1700)

單元測試驗證

public class ByteOrderUtilsTest {
    @Test public void testIntRoundTrip() {
        int[] cases = {0, 1, -1, 127, 128, 255, 65535, Integer.MAX_VALUE, Integer.MIN_VALUE};
        for (int v : cases) {
            byte[] bytes = ByteOrderUtils.int2byte(v);
            int back = ByteOrderUtils.byteArrayToInt(bytes);
            assertEquals(v, back);
        }
    }
    @Test public void testLongRoundTrip() {
        long[] cases = {0L, 1L, -1L, 255L, 65535L, Long.MAX_VALUE, Long.MIN_VALUE};
        for (long v : cases) {
            byte[] bytes = ByteOrderUtils.long2byte(v);
            long back = ByteOrderUtils.byteArrayToLong(bytes);
            assertEquals(v, back);
        }
    }
}

替代方案:JDK 内建 / 第三方庫

  • ByteBuffer(NIO):ByteBuffer.allocate(4).putInt(v).array(),支援大小端切換 .order(ByteOrder.LITTLE_ENDIAN)。
  • DataOutputStream / DataInputStream:流式寫入/讀取。
  • Netty ByteBuf、Protocol Buffers、FlatBuffers:高效能序列化框架。

總結

手寫位運轉轉換能深入理解二進制表示與端序本質。生產環境建議優先使用 ByteBuffer 或成熟序列化框架,減少手工錯誤,提升可維護性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved