简体   繁体   中英

Get unsigned integer from byte array in java

I need to get unsigned integer from byte array. I understand that java doesn't support unsigned primitives, and I have to use higher primitive (long) to get unsigned int. Many people usually suggest solution like:

public static long getUnsignedInt(byte[] data)
{
    ByteBuffer bb = ByteBuffer.wrap(data);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    return bb.getInt() & 0xffffffffl;
}

But this is not smart since we have to get signed integer then convert it to unsigned which of course may result in overflow exception. I saw other solutions using BigInteger or new java 8 unsigned feature, but I couldn't get it to do what I want.

But this is not smart since we have to get signed integer then convert it to unsigned which of course may result in overflow exception.

There is no such thing as an "overflow exception." Your solution will always work exactly correctly and efficiently. Stop worrying.

You could do something like this:

public static long getUnsignedInt(byte[] data) {
    long result = 0;

    for (int i = 0; i < data.length; i++) {
        result += data[i] << 8 * (data.length - 1 - i);
    }
    return result;
}

You basically create an empty long and shift the bytes into it. You can see this in action in the java.io.DataInputStream.readInt() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM