Reputation: 101
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?
Upvotes: 5
Views: 9344
Reputation: 29680
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
Upvotes: 3
Reputation: 93978
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.
Upvotes: 1
Reputation: 53657
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
Upvotes: 1
Reputation: 888
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.
Upvotes: 0
Reputation: 1053
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.
Upvotes: 8
Reputation: 5903
Just pass a index parameter to your proc
void proc(byte[] array, int index)
{
for (int i = index; i < array.length; ++i)
{
// do something
}
}
Upvotes: 1