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

后端 未结 7 724
梦如初夏
梦如初夏 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:32

    You need to know the endianness of your bytes.

    Assuming (like @WhiteFang34) that bytes is a byte[] of length 4, then...

    Big-endian:

    int x = java.nio.ByteBuffer.wrap(bytes).getInt();
    

    Little-endian:

    int x = java.nio.ByteBuffer.wrap(bytes).order(java.nio.ByteOrder.LITTLE_ENDIAN).getInt();
    
    0 讨论(0)
提交回复
热议问题