Java (Android) - putInt 上的 BufferOverflowException
Java (Android) - BufferOverflowException on putInt
我试试这个代码:
byte arr[] = ByteBuffer.allocate(2).putInt(1).array()
但是它失败了 BufferOverflowException
。
1 太大而不能存储在 2 个字节中吗?还是我的问题出在其他地方?
Is 1 too big to be stored in 2 bytes ?
嗯,int
是...putInt
总是写入 4 个字节。来自 documentation for ByteBuffer.putInt
Throws:
BufferOverflowException - If there are fewer than four bytes remaining in this buffer
如果您只想输入 two-byte 整数,请改用 putShort
。如果您想以 variable-width 编码存储数据(其中 space 取决于值),您可能需要自己编写代码。
来自方法的 javadoc putInt
:
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
您只分配了 2 个字节,所以 BufferOverflowException
:
Unchecked exception thrown when a relative put operation reaches the target buffer's limit.
您可以解决扩展到 4 个字节的缓冲区或使用 putShort 仅使用 2 个字节来存储数字 1。
ByteBuffer.putInt(1)
将整数值放入缓冲区。整数的长度为 4 字节(32 位)。
我试试这个代码:
byte arr[] = ByteBuffer.allocate(2).putInt(1).array()
但是它失败了 BufferOverflowException
。
1 太大而不能存储在 2 个字节中吗?还是我的问题出在其他地方?
Is 1 too big to be stored in 2 bytes ?
嗯,int
是...putInt
总是写入 4 个字节。来自 documentation for ByteBuffer.putInt
Throws:
BufferOverflowException - If there are fewer than four bytes remaining in this buffer
如果您只想输入 two-byte 整数,请改用 putShort
。如果您想以 variable-width 编码存储数据(其中 space 取决于值),您可能需要自己编写代码。
来自方法的 javadoc putInt
:
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
您只分配了 2 个字节,所以 BufferOverflowException
:
Unchecked exception thrown when a relative put operation reaches the target buffer's limit.
您可以解决扩展到 4 个字节的缓冲区或使用 putShort 仅使用 2 个字节来存储数字 1。
ByteBuffer.putInt(1)
将整数值放入缓冲区。整数的长度为 4 字节(32 位)。