开发者

convert a pointer of array in Java

开发者 https://www.devze.com 2023-02-08 07:29 出处:网络
I\'m trying to convert a p开发者_如何转开发rogram in c to Java. I don\'t know c programming, I\'d like to understand a bit btw.

I'm trying to convert a p开发者_如何转开发rogram in c to Java. I don't know c programming, I'd like to understand a bit btw.

well I've got those functions in C:

static int memcmp( Byte *a, Byte *b, int len) {
    int i;
    for (i = 0; i < len; i++) 
        if (a[i] != b[i]) 
            return 0;
    return 1;
}

static int rfind(Byte *data, int pos, int leng) {
    int i;
    for (i = pos - leng; i > -1; i--) 
        if (memcmp(data+i, data+pos, leng)) 
            return i;
    return pos;
}

that I can't workout. It seems the function memcmp compare two blocks of memory. When i get the size of data:

printf("size %d \n", sizeof(data));

I got 8 for the result while the orignal size can 32 or 40 (any good documentation about pointers is welcome).

Anyone who could help me to translate this bit to Java will have all my gratitude (and even more). Thanks


Java doesn't have pointers, so you can't translate the code directly. In C, you can treat pointers as arrays, whereas in Java you will need to use indexes into the same array. This is more or less as direct a translation as I can come up with:

public int rfind(byte[] data, int pos, int len) {
    for (int i = pos - len; i > -1; i--) {
        if (memcmp(data, i, pos, len)) {
            return i;
        }
    }
    return pos;
}

public boolean memcmp(byte[] data, int idx1, int idx2, int len) {
    for (int i = idx1; i <= len; i++) {
        if (data[i] != data[idx2 + i]) {
            return false;
        }
    }
    return true;
}

EDIT

As ayush points out, if the data array is an ASCII string, you can get the same result in a much simple way by using library calls.

String str = new String(data); // convert data byte array to String
String sub = str.substring(pos, len); // substring pointed to by pos
int rfindResult = str.lastIndexOf(sub);


to compare string and byte array's you can use Arrays.equals().

as far as rfind goes you can use lastIndexOf() http://forums.devshed.com/java-help-9/the-equivanent-of-rfind-in-java-603139.html

0

精彩评论

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

关注公众号