java - 将 int 转换为 byte 时出现 BufferOverflowException

标签 java arrays byte bytebuffer

我有一个从 0 到 32767 的计数器

在每一步,我都想将 counter (int) 转换为 2 字节数组。

我试过了,但是我得到了一个BufferOverflowException异常:

byte[] bytearray = ByteBuffer.allocate(2).putInt(counter).array();

最佳答案

是的,这是因为 int 在缓冲区中占用 4 个字节,无论其值如何。

ByteBuffer.putInt对此和异常(exception)情况都很清楚:

Writes four bytes containing the given int value, in the current byte order, into this buffer at the current position, and then increments the position by four.

...

Throws:
BufferOverflowException - If there are fewer than four bytes remaining in this buffer

要写入两个字节,请改用 putShort...并且最好将 counter 变量也更改为 short,以使很清楚预期的范围是什么。

关于java - 将 int 转换为 byte 时出现 BufferOverflowException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32626533/

相关文章:

java - 如何使用 Java 8 中的比较器按参数对流进行排序?

java - 如何在 Spark 中运行分析?

java - 寻找数组中最短的项?

python - Python 中指定索引的数组值求和

java - 在java中读取c++字节位域

JavaFX 从 AnchorPane 中删除对象

java - 处理 onClick 事件时 getView 出现空指针异常

java - 如何使用匿名类从 Jcombobox 数组中获取值

C - 如何在内存级别进行算术转换?

java - Java中字节到整数再到字符串的转换