从 java 中的字节数组中获取无符号整数

Get unsigned integer from byte array in java

我需要从字节数组中获取无符号整数。我知道 java 不支持无符号基元,我必须使用更高的基元(long)来获得无符号整数。许多人通常建议解决方案如下:

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

但这并不聪明,因为我们必须得到有符号整数然后将其转换为无符号整数,这当然可能导致溢出异常。我看到其他解决方案使用 BigInteger 或新的 java 8 unsigned 功能,但我无法让它做我想做的事。

你可以这样做:

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;
}

您基本上创建了一个空的 long 并将字节移入其中。 您可以在 java.io.DataInputStream.readInt() 方法中看到这一点。

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.

不存在 "overflow exception." 您的解决方案将始终准确有效地工作。别担心了。