如何在Java中使用ByteBuffer的Wrap方法

Thi*_*mer 6 java arrays byte bytebuffer type-conversion

好吧,所以我正在查找从字节数组转换为java中的数值的最佳方法是什么,我遇到了这个链接.第二个答案提到了ByteBuffer类的使用.对于那些不希望点击链接的人,最初问题是否我有:

byte[] by = new byte[8];
Run Code Online (Sandbox Code Playgroud)

如何将其转换为int?答案是......

ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 0, 0, 0, 0, 4});
long l = bb.getLong();

System.out.println(l);
Run Code Online (Sandbox Code Playgroud)

结果

4
Run Code Online (Sandbox Code Playgroud)

这真是太棒了,但我只是想在走这条路之前确认一些事情.

假设我之前读取的字节数组长度为8个字节.

byte[] oldByte = new byte[8];
Run Code Online (Sandbox Code Playgroud)

那我呢......

ByteBuffer bb = ByteBuffer.wrap(new byte[] {oldByte[2], oldByte[3]});
int intValue = bb.getInt();
Run Code Online (Sandbox Code Playgroud)

是否会以与前一个示例相同的方式读取/读取?

and*_*ler 7

The documentation for the ByteBuffer class specifies that the getInt() method reads the next four bytes, so if you are only passing two bytes to the call to wrap, you will get a BufferUnderflowException:

抛出:BufferUnderflowException - 如果此缓冲区中剩余的字节少于四个