java - Generate new byte[] from existing byte[] -


i generate "new" byte array existing one, without having allocate heap. in other words, "new" byte array should share same underlying data existing one. catch new byte array have different length.

byte[] buffer = { 0x01, 0x02, 0x04, 0x08, 0x10 }; byte[] shared = slice(buffer, 1, 3); /* shared should { 0x02, 0x04, 0x08 } , have length of 3 */ 

i'm doing because have byte array need extract packet, pass packet single-parameter method takes byte[]. want avoid making copy of data contained in packet. purposes, can assumed contents of buffer not change within scope of shared.

is possible? seems common thing 1 want when working buffers. in advance,

no, not possible in java have different byte[] (partly) share same memory.

instead of using byte[], use java.nio.bytebuffer allow slice buffer in way want to.

bytebuffer buffer = bytebuffer.wrap(new byte[]{ 0x01, 0x02, 0x04, 0x08, 0x10 });  buffer.position(1); buffer.limit(4);  bytebuffer shared = buffer.slice(); 

note bytebuffer returned buffer.slice() refers same underlying byte array original buffer.


Comments

Popular posts from this blog

ubuntu - How to disable Kernel Module Signing in linux -

java - Ebean enhancement ignores a model -

How to combine associative arrays in bash? -