How can I convert a 4-byte array to an integer?

后端 未结 7 749
梦如初夏
梦如初夏 2020-12-24 02:42

I want to perform a conversion without resorting to some implementation-dependent trick. Any tips?

7条回答
  •  甜味超标
    2020-12-24 03:22

    Assuming bytes is a byte[4] of an integer in big-endian order, typically used in networking:

    int value = ((bytes[0] & 0xFF) << 24) | ((bytes[1] & 0xFF) << 16)
            | ((bytes[2] & 0xFF) << 8) | (bytes[3] & 0xFF);
    

    The & 0xFF are necessary because byte is signed in Java and you need to retain the signed bit here. You can reverse the process with this:

    bytes[0] = (byte) ((value >> 24) & 0xFF);
    bytes[1] = (byte) ((value >> 16) & 0xFF);
    bytes[2] = (byte) ((value >> 8) & 0xFF);
    bytes[3] = (byte) (value & 0xFF);
    

提交回复
热议问题