Tobia Tobia - 3 months ago 34
Java Question

Convert DWORD byte array to a unsigned long number

I want the unsigned value of a little-endian DWORD byte array.

This is what I wrote:

private long getUnsignedInt(byte[] data) {
long result = 0;
for (int i = 0; i < data.length; i++) {
result += (data[i] & 0xFF) << 8 * (data.length - 1 - i);
}
return result;
}


Is it right?

Answer

If by DWORD you mean 32 bits unsigned int, try this

    public long readUInt(byte[] data) {
            return (
                ((long)(data[0] & 0xFF) << 24) |
                ((long)(data[1] & 0xFF) << 16) |
                ((long)(data[2] & 0xFF) << 8) |
                ((long)(data[3] & 0xFF) << 0));
    }

BTW, your code seems correct, but this one is faster.