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'
Droidum
  • 440
  • 2
  • 9
  • 2
    Why is it a performance killer? How have you tested this? – Bob Dalgleish Sep 08 '15 at 12:46
  • One of the answers to [memcpy function in C++ to Java equivalent](http://stackoverflow.com/questions/6060163/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. – Bernhard Barker Sep 08 '15 at 12:50
  • You may be able to do that using the unsafe - not sure... – assylias Sep 08 '15 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. – Droidum Sep 08 '15 at 13:18

1 Answers1

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();
Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • 1
    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)));` – Eran Sep 08 '15 at 12:42
  • 1
    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. – Kayaman Sep 08 '15 at 12:48
  • Well ok even if the Buffer is not faster at least it keeps this terrible syntax away from me :-) – Droidum Sep 08 '15 at 13:20