Reputation: 45491
I have an int[] in java which i want to convert to a byte[].
Now the usual way to do this would be to create a new byte[] 4 times the size of the int array and copy all the ints byte by byte into the new byte array.
However the only reason to do this is because of java's type safety rules. An int array is already a byte array. Its just that java doesnt allow casting an int[] to a byte[] and then using it as a byte[].
Is there any way, maybe using jni, to make an int array look like a byte array to java ?
Upvotes: 2
Views: 610
Reputation: 423
Depending on your precise requirements, you may be able to use NIO's java.nio.ByteBuffer
class. Do your initial allocation as a ByteBuffer, and use it's getInt
and putInt
methods to access int values. When you need to access the buffer in terms of bytes, you may use the get
and put
methods. ByteBuffer also has an asIntBuffer
method which changes the default get and put behavior to int instead of byte.
If you're using JNI, a directly allocated ByteBuffer (in some instances) permits direct pointer access in your C code.
http://java.sun.com/javase/6/docs/api/java/nio/ByteBuffer.html
For example,
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
// …
int[] intArray = { 1, 2, 3, 4 };
ByteBuffer byteBuffer = ByteBuffer.allocate(data.length * 4);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(intArray);
byte[] byteArray = byteBuffer.array();
Upvotes: 4
Reputation: 62769
If you really really had to, you could use external calls into C to do this, but I'm pretty sure it can't be done within the language.
I'm also really curious as to what the existing code looks like and how much extra speed you are expecting.
You know the rules of optimization, right?
Upvotes: 1
Reputation: 272307
No. There isn't a capability to implement an object with a native Java array interface.
It sounds to me like you want an object wrapping your int[], and present methods to access it in a byte-array-wise fashion. e.g.
public class ByteArrayWrapper {
private int[] array;
public int getLength() {
return array.length * 4;
}
public byte get(final int index) {
// index into the array here, find the int, and then the appropriate byte
// via mod/div/shift type operations....
int val = array[index / 4];
return (byte)(val >> (8 * (index % 4)));
}
}
(the above is not tested/compiled etc. and is dependent upon your byte-ordering requirements. It's purely illustrative)
Upvotes: 9