Reputation: 101
i have an array of bytes which needs to be repackaged to an array of longs. the input byte array is of unknown size (roughly from 0 to a few hundred). the long array needs to come out right aligned ie the lowest index long should be padded with zeros and all others should be full of the input bytes: . (b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11) --> (xxxxb0b1b2b3, b4b5b6b7b8b9b10b11)
where b1,b2 etc is a given byte. i have a solution but it isnt very neat or readable:
// outArr has length (inArr.length+7)/8
for (int i = 0; i < inArr.length ; i++) {
outArr[outArr.length - i/8 - 1] |= ((long)inArr[inArr.length - i - 1]) << (i % 8) * 8;
}
is there a less ugly way of doing this?
Upvotes: 5
Views: 1775
Reputation: 5095
There may be more elegant ways of doing it, but one way could be to use a java.nio buffer to convert it. Because of the need to align the input array to 8 bytes chunks, it requires a few more steps:
int padding = outArr.length * 8 - inArr.length;
ByteBuffer buffer = ByteBuffer.allocate(inArr.length + padding)
.put(new byte[padding]).put(inArr);
buffer.flip();
buffer.asLongBuffer().get(outArr);
Upvotes: 2