开发者

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

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

In C Language

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);
}

is not worked.

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);
}

is only worked.

But, I开发者_如何学运维 don't like arraycopy.

How can I solve this problem?


You could always extend your "proc" function to take 3 parameters like so:

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

That's the best way to mimic C-array functionality in Java.


The class java.util.Arrays has some useful methods like:

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

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

more: copyOfRange


Just pass a index parameter to your proc

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


Try with the following code instead of 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];



        }

Thanks Deepak


Since none of the answers included ByteBuffer, I'll show another way:

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 (the buf argument to proc()) will be visible to the underlying array.


In C, an array is just a pointer to somewhere in memory, and buf+i has meaning (it means a place in memory i bytes on - which is also an array)

In java an Array is an object with length and code attached. There is no way to have a reference to an "array inside an array", and the "+" operator has no meaning.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜