4

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?

  • please take a look at http://stackoverflow.com/questions/4485128/how-do-i-convert-long-to-byte-and-back-in-java – Ron Klein Jun 12 '16 at 20:07

1 Answers1

2

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);
Per Huss
  • 4,755
  • 12
  • 29
  • `ByteByffer.wrap(inArr)` is yetl a bit shorter. And `order(LITTLE_ENDIAN)` might be needed. But indeed ByteBuffer is _the_ solution. – Joop Eggen Jun 12 '16 at 22:43
  • Yes, that would be shorter, but it would not solve the _whole_ problem because of the needed padding, as you would need to have a correctly padded byte array first. That's what I'm building building the byte buffer with two `put()` and `flip()`. Regarding the order; the default `BIG_ENDIAN` is the correct one. – Per Huss Jun 13 '16 at 05:09