gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:59:12 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com