Java 字节数组到 int 函数给出负数

Java byte array to int function giving negative number

我有这样的功能:

static int byteArrayToInt(byte[] bytes) {
         return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
}

应该将 4 个字节的 byteArray 转换为 int。

hexBinary 中的字节数组is:E0C38881

预期输出应该是:3770910849 但我得到:-524056447

我需要做什么来解决这个问题?

3770910849 高于 Integer.MAX_VALUE。如果您需要正值,请使用 long 而不是 int。

例如:

static long byteArrayToInt(byte[] bytes) {
     return (long)((bytes[0] << 24) | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF)) & 0xffffffffL;
}

这是我用来让它工作的方法:

static long getLong(byte[] buf){
        long l = ((buf[0] & 0xFFL) << 24) |
                 ((buf[1] & 0xFFL) << 16) |
                 ((buf[2] & 0xFFL) << 8) |
                 ((buf[3] & 0xFFL) << 0) ;
        return l;
}