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
OLDER ANSWER
edit : Based on comments (understanding Question better)
To make your
toLong
function handle both negative & positive numbers try this:Below is related
bytesToHex
function (re-factored to work out-of-box with anybyte[]
input...)