Buffer 转 IntBuffer
时间: 2023-09-08 18:16:44 浏览: 58
在 Java 中,可以使用 `ByteBuffer` 类和 `IntBuffer` 类来实现 `Buffer` 转 `IntBuffer`。下面是一个示例代码:
```java
import java.nio.*;
public class BufferToIntBuffer {
public static void main(String[] args) {
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
byteBuffer.putInt(123); // 将 int 类型的数据放入 ByteBuffer 中
byteBuffer.flip(); // 切换 ByteBuffer 为读模式
IntBuffer intBuffer = byteBuffer.asIntBuffer(); // 将 ByteBuffer 转换为 IntBuffer
int intData = intBuffer.get(); // 从 IntBuffer 中读取数据
System.out.println(intData); // 输出结果为 123
}
}
```
在上述示例代码中,我们首先创建一个 4 个字节大小的 `ByteBuffer` 对象,并通过 `putInt` 方法将一个 int 类型的数据放入 `ByteBuffer` 中。然后通过 `flip` 方法切换 `ByteBuffer` 为读模式,再调用 `asIntBuffer` 方法将 `ByteBuffer` 转换为 `IntBuffer`。最后通过 `get` 方法从 `IntBuffer` 中读取数据,得到一个 int 类型的结果。