3

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'
4
  • 2
    Why is it a performance killer? How have you tested this? Commented Sep 8, 2015 at 12:46
  • One of the answers to memcpy function in C++ to Java equivalent might help, although if optimizing this is required for performance and/or you need this sort of low-level access, you probably shouldn't be using Java. Commented Sep 8, 2015 at 12:50
  • You may be able to do that using the unsafe - not sure... Commented Sep 8, 2015 at 13:06
  • I can't imagine this assembling procedure with four value accesses and three shifts and ors is roughly as fast as a simple int copy that handles four bytes in one operation. Unfortunately I forgot to mention I do android programming so there is no unsafe class. Commented Sep 8, 2015 at 13:18

1 Answer 1

4

The easiest way to do this is with Buffers.

ByteBuffer b = ByteBuffer.allocate(1024);
// Fill the bytebuffer and flip() it
IntBuffer i = b.asIntBuffer();
Sign up to request clarification or add additional context in comments.

3 Comments

I don't think it improves the performance over the OPs original code. When you fetch an int from the IntBuffer, It ends up calling Bits.makeInt which does what the OP wanted to avoid - return (int)((((b3 & 0xff) << 24) | ((b2 & 0xff) << 16) | ((b1 & 0xff) << 8) | ((b0 & 0xff) << 0)));
While it may not affect performance as much (although with direct buffers it should be quicker), it'll at least prevent him from writing all that code himself and possibly making mistakes.
Well ok even if the Buffer is not faster at least it keeps this terrible syntax away from me :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.