Converting a C++ Checksum function to Java

Posted by user1897599 on Stack Overflow See other posts from Stack Overflow or by user1897599
Published on 2012-12-12T11:48:39Z Indexed on 2012/12/14 11:04 UTC
Read the original article Hit count: 179

Filed under:
|
|

I'm trying to convert this C++ checksum to Java but for the time being I've failed. What am I doing wrong?

What is it supposed to do? It is supposed to return a positive checksum for a buffer in OpenGL

Here's the C part.

DWORD QuickChecksum(DWORD *data, int size){

if(!data) {
    return 0x0; 
}

DWORD sum;
DWORD tmp;
sum = *data;

for(int i = 1; i < (size/4); i++)
{
    tmp = data[i];
    tmp = (DWORD)(sum >> 29) + tmp;
    tmp = (DWORD)(sum >> 17) + tmp;
    sum = (DWORD)(sum << 3)  ^ tmp;
}

return sum;
}

And here is what I have tried in Java. As far As I know DWORD is 32bit so I use int in a long to get a unsigned int which should be done in java with >>>?

I've been looking at this problem so much now that I've grown blind to it.

public static long getChecksum(byte[] data, int size) {
    long sum, tmp;
    sum = getInt(new byte[]{data[0], data[1], data[2], data[3]},true) & 0xFF;
    for(int I = 4; I < data.length; I += 4)
    {
        tmp = getInt(new byte[]{data[I],data[I+1],data[I+2],data[I+3]},true) & 0xFF;
        tmp = (sum >>> 29) + tmp;
        tmp = (sum >>> 17) + tmp;
        sum = (sum << 3) ^ tmp;
    }
    return sum & 0xFF;
}

private static int getInt(byte[] bytes, boolean big) {
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    return bb.getInt();
}

Thank you all for your help!

© Stack Overflow or respective owner

Related posts about java

Related posts about c++