Java byte 数组与 int long 互转

    技术2024-12-17  13

    单个 byte 直接转换为 int long 会有符号问题,可和 0xFF 与运算解决。

    另外一种方法是利用 ByteBuffer 类。

    public static void intToByteArray(int intValue, byte[] bytes) { bytes[0] = (byte) ((intValue >> 24) & 0xFF); bytes[1] = (byte) ((intValue >> 16) & 0xFF); bytes[2] = (byte) ((intValue >> 8) & 0xFF); bytes[3] = (byte) (intValue & 0xFF); } public static int byteArrayToInt(byte[] bytes) { return byteArrayToInt(bytes, 0); } public static int byteArrayToInt(byte[] bytes, int offset) { return (bytes[offset] & 0xFF) << 24 | (bytes[offset + 1] & 0xFF) << 16 | (bytes[offset + 2] & 0xFF) << 8 | bytes[offset + 3] & 0xFF; } public static void longToByteArray(long longValue, byte[] bytes) { bytes[0] = (byte) ((longValue >> 56) & 0xFF); bytes[1] = (byte) ((longValue >> 48) & 0xFF); bytes[2] = (byte) ((longValue >> 40) & 0xFF); bytes[3] = (byte) ((longValue >> 32) & 0xFF); bytes[4] = (byte) ((longValue >> 24) & 0xFF); bytes[5] = (byte) ((longValue >> 16) & 0xFF); bytes[6] = (byte) ((longValue >> 8) & 0xFF); bytes[7] = (byte) (longValue & 0xFF); } public static long byteArrayToLong(byte[] bytes) { return byteArrayToLong(bytes, 0); } public static long byteArrayToLong(byte[] bytes, int offset) { return ((long) bytes[offset] & 0xFF) << 56 | ((long) bytes[offset + 1] & 0xFF) << 48 | ((long) bytes[offset + 2] & 0xFF) << 40 | ((long) bytes[offset + 3] & 0xFF) << 32 | ((long) bytes[offset + 4] & 0xFF) << 24 | ((long) bytes[offset + 5] & 0xFF) << 16 | ((long) bytes[offset + 6] & 0xFF) << 8 | (long) bytes[offset + 7] & 0xFF; }
    Processed: 0.062, SQL: 9