Java byte array and int long conversion

Direct conversion of a single byte to int long will cause a sign problem, which can be solved with the 0xFF AND operation.

Another method is to use the ByteBuffer class.

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

Guess you like

Origin blog.csdn.net/hegan2010/article/details/107118632