How can I use part of byte [] without arraycopy?

I wonder how to use part of byte [] without arraycopy?

In language C

char buf[100];
int i;

for (i = 0; i < 100; i += 10) {
    proc(buf + i);
}

But in Java ,

byte[] buf = new byte[100];
int i;

for (i = 0; i < 100; i += 10) {
    proc(buf + i);
}

does not work.

byte[] buf = new byte[100];
int i;

for (i = 0; i < 100; i += 10) {
    byte[] temp = new byte[10];
    System.arraycopy(buf, i, temp, 0, 10);
    proc(temp);
}

only works.

But I do not like arracycopy.

How can I solve this problem?

+3
source share
6 answers

You can always expand your "proc" function to select 3 options:

proc(byte[] a, int offset, int length)

This is the best way to simulate the functionality of a C array in Java.

+8
source

There java.util.Arraysare several useful methods in the class , for example:

byte[] buf = new byte[100];
int i;

for (i = 0; i < 100; i += 10) {
    proc(Arrays.copyOfRange(buf, i, buf.length));
}

more details: copyOfRange

+3
source

proc

void proc(byte[] array, int index)
{
    for (int i = index; i < array.length; ++i)
    {
        // do something   
    }     
}
+1

arraycopy

byte[] buf = new byte[100];
        int i;

        for (i = 0; i < 100; i += 10) {
            byte[] temp = new byte[10];
                  temp[i%10] = buf[i];



        }

+1

ByteBuffer, :

import java.nio.ByteBuffer;

public class ProcByteBuffer {

    private static final int BUF_SIZE = 10;
    private static final int BIG_BUF_SIZE = 10 * BUF_SIZE;

    public static void proc(final ByteBuffer buf) {

        // for demo purposes
        while (buf.hasRemaining()) {
            System.out.printf("%02X", Integer.valueOf(buf.get() & 0xFF));
        }
    }

    public static void main(String[] args) {
        final ByteBuffer bigBuf = ByteBuffer.allocate(BIG_BUF_SIZE);

        // for demo purposes
        for (int i = 0; i < BIG_BUF_SIZE; i++) {
            bigBuf.put((byte) i);
        }
        bigBuf.position(0);

        for (int i = 0; i < BIG_BUF_SIZE; i += BUF_SIZE) {
            bigBuf.position(i);
            bigBuf.limit(i + BUF_SIZE);
            proc(bigBuf.slice());
        }
    }
}

Any changes to the slice (buf argument for proc ()) will be visible to the underlying array.

+1
source

In C, an array is just a pointer to somewhere in memory, and buf + I make sense (this means a place in memory, I bytes on is also an array)

In java, an array is an object with length and code. It is impossible to refer to the "array inside the array", and the "+" operator does not make sense.

0
source

All Articles