Reputation: 10412
I am working on an android application. I was using a static function in a library, that takes byte[]
as a parameter.
I used to pass a hard code byte array containing 36 bytes:
new byte[]{-13, 35, -92, -79, 47, -51, -57, 39, ......};
But in the latest release, they changed the function to take a long[]
instead. So I can no longer pass my byte array.
How can I convert from my saved byte[] to a long[] in order to still use this function with the same value as before?
Is there a conversion from byte[]
to long[]
? To my knowledge 'byte[]' can be converted to long
but not to long array.
Any help on this is greatly appreciated
Upvotes: 3
Views: 844
Reputation: 1997
It is one of the simplest question you should have tried it id IDE.
byte[] bytesArr = { 0, 6, 36, -84, 113, 125, -118, -47 };
long[] longArr = new long[bytesArr.length];
for (int i = 0; i < bytesArr.length; i++) {
longArr[i] = bytesArr[i];
}
Also, it is possible to convert long[] to byte[] but you will loose all values which are not in range of byte i.e. -128 to 127.
Upvotes: 0
Reputation: 563
I guess you will need to convert 4 bytes to one long. So the most simple solution would be using ByteBuffers.
long[] byteToLong(byte[] array) {
ByteBuffer byteBuffer = ByteBuffer.wrap(array);
LongBuffer longBuffer = byteBuffer.asLongBuffer();
long[] result = new long[longBuffer.capacity()];
longBuffer.get(result);
return result;
}
Note: this produces BigEndian values - not sure what your API needs.
Upvotes: 1