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?


No I am afreaid that is big endian.

public long readUInt(byte[] data) {
    // If you want to tackle different lengths for little endian:
    //data = Arrays.copyOf(data, 4);
    return ByteBuffer.wrap(data)
        .getInt() & 0xFF_FF_FF_FFL;

The above does a 4 byte to (signed) int conversion and then make it unsigned.

Leave a Reply

Your email address will not be published. Required fields are marked *