byte array with variable length to number

2.2k views Asked by At

I need to convert a number to byte array and then back to number. The problem is that the byte array is of variable size, so I need to convert a number given his byte length, the methods that I came up with are those: (Java)

private static byte[] toArray(long value, int bytes) {
    byte[] res = new byte[bytes];

    final int max = bytes*8;
    for(int i = 1; i <= bytes; i++)
        res[i - 1] = (byte) (value >> (max - 8 * i));

    return res;
}

private static long toLong(byte[] value) {
    long res = 0;

    for (byte b : value)
        res = (res << 8) | (b & 0xff);

    return res;
}

Here I use a long because 8 is the max bytes we can use. This method works perfectly with positive numbers but I can't seem to make the decoding work with negatives.

EDIT: to test this I've tried with processing the value Integer.MIN_VALUE + 1 (-2147483647) and 4 bytes

2

There are 2 answers

7
VC.One On BEST ANSWER

After accepting this as working solution, the Asker made some further optimizations.
I have included their own
linked code below for reference :

private static long toLong(byte[] value) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    final byte val = (byte) (value[0] < 0 ? 0xFF : 0);

    for(int i = value.length; i < Long.BYTES; i++)
        buffer.put(val);

    buffer.put(value);
    return buffer.getLong(0);
}

OLDER ANSWER

edit : Based on comments (understanding Question better)

To make your toLong function handle both negative & positive numbers try this:

private static long toLong(byte[] value) 
{
    long res = 0;
    int tempInt = 0;
    String tempStr = ""; //holds temp string Hex values

    tempStr = bytesToHex(value);

    if (value[0] < 0 ) 
    { 
        tempInt = value.length;
        for (int i=tempInt; i<8; i++) { tempStr = ("FF" + tempStr); }

        res = Long.parseUnsignedLong(tempStr, 16); 
    }
    else { res = Long.parseLong(tempStr, 16); }

    return res;

}

Below is related bytesToHex function (re-factored to work out-of-box with any byte[] input...)

public static String bytesToHex(byte[] bytes)
{ String tempStr = ""; tempStr = DatatypeConverter.printHexBinary(bytes); return tempStr; }


4
Andrii Abramov On

Take a look at Apache Common Conversion.intToByteArray util method.

JavaDoc:

Converts a int into an array of byte using the default (little endian, Lsb0) byte and bit ordering