Hello, everyone!
I need to be able to convert byte arrays to/from other primitive type arrays, but instead of casting, I need type punning. Correct term for raw copy without casting?
I thought it would be possible to do the following:
// idea: byte[12] -> int[3], and int[3] -> byte[12]
int[] ints;
ByteBuffer bb = ByteBuffer.wrap(
new byte[]{ 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3 });
IntBuffer ib = bb.asIntBuffer();
ints = ib.array(); // java.lang.UnsupportedOperationException
ints = ib.duplicate().array(); // java.lang.UnsupportedOperationException
Unfortunately, it seems that bb.asIntBuffer()
is not creating a new IntBuffer by copying the content "bitwise" or "raw", but creates a new "view" on existing ByteBuffer. That's why .array()
is intended to fail.
I browsed around in JDK's sources, and found few classes, which are used by all these buffer classes and would do the stuff I need, but are internal (such as the class Unsafe
).
While I think that my goal could be achieved by wrapping the byte buffer in some ObjectInputStream
and read the primitive values by .readInt()
, I think it would be a messy and slow workaround.
So, are there any other solutions possible without doing magical primitive type arithmetics (shifting, checking endians, ...)?
NOTE: I need both directions: byte[12] -> int[3], and int[3] -> byte[12]