Droidum
Droidum

Reputation: 434

copy java array "over" another

I wonder if there really - as my search shows - is no way to perform a bytewise copy of one array into another array of different primitive type. I have a byte[] from a file that represents a int[] in memory. I could do shifts like

myints[i] = (mybytes[0] << 24) || (mybytes[1] << 16) || (mybytes[2] << 8) || mybytes[0];

but this performance killer can't be the preferred way? Is there nothing like this?

byte[] mybytes = ... coming from file  
int[] myints = new int[mybytes.length / 4];  
MagicCopyFunction: copy mybytes.length bytes from 'mybytes' into 'myints'

Upvotes: 3

Views: 103

Answers (1)

Kayaman
Kayaman

Reputation: 73528

The easiest way to do this is with Buffers.

ByteBuffer b = ByteBuffer.allocate(1024);
// Fill the bytebuffer and flip() it
IntBuffer i = b.asIntBuffer();

Upvotes: 4

Related Questions