aman
aman

Reputation: 77

How to convert a long value (with values upto 40 bits only) into a 5-byte array?

I need to convert parameter(long variable) having size up-to 40 bits to a 5-byte size array in Java. And, then also retrieve value from that 5-byte size array to a long variable again. Have tried to convert using below code, but getting different number after conversion. Value passed in the method is 1099511627.00

public static byte[] longToBytes(long l) {
    byte[] result = new byte[5];
    for (int i = 4; i >= 0; i--) {
        result[i] = (byte)(l & 0x1F);
        l >>= 4;
    }
    return result;
}

public static long bytesToLong(final byte[] b) {
    long result = 0;
    for (int i = 0; i < 5; i++) {
        result <<= 5;
        result |= (b[i] & 0x1F);
    }
    return result;
}

Upvotes: 2

Views: 235

Answers (1)

StartsMercury
StartsMercury

Reputation: 64

public static byte[] longToBytes(long l, int size) {
    byte[] result = new byte[size];
    for (int i = size - 1, min = Math.max(size - 8, 0); i >= min; i--) {
        result[i] = (byte) (l & 0xFF);
        // take out 8-bits as the byte is stored
        l >>= 8;
    }
    return result;
}

public static long bytesToLong(final byte[] bs) {
    long result = 0;
    for (int i = Math.max(bs.length - 8, 0); i < bs.length; i++) {
        // make 8-bit space for the next byte
        result <<= 8;
        result |= (long) b & 0xFF;
    }
    return result;
}

For 5 bytes only just do longToBytes(l, 5).

Upvotes: 0

Related Questions