简体   繁体   中英

Java byte array to int function giving negative number

I have a function like so:

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

Which should convert a byteArray of 4 bytes to an int.

The byte array in hexBinary is:E0C38881

And the expected output should be: 3770910849 But I am getting: -524056447

What do I need to do to fix this?

3770910849 is higher than Integer.MAX_VALUE . If you require a positive value, use long instead of int.

For example :

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

This is what I used to get it working:

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

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