我有一个从 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/