【问题标题】:BufferOverflowException while converting int to byte将 int 转换为 byte 时出现 BufferOverflowException
【发布时间】:2015-09-17 09:10:15
【问题描述】:

我有一个从 0 到 32767 的 counter

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

我已经尝试过了,但我得到了 BufferOverflowException 异常:

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

【问题讨论】:

  • 好吧,你期待什么?您尝试将 4 个字节放入一个 2 个字节长的缓冲区中。
  • 你想达到什么目的?
  • 将最大数量更改为 32767 如果我通过移位来做到这一点,则值 128 将是 -128。但我需要正字节

标签: java arrays byte bytebuffer


【解决方案1】:

是的,这是因为 int 在缓冲区中占用 4 个字节,而不管值如何。

ByteBuffer.putInt 清楚这一点和例外:

以当前字节顺序将包含给定 int 值的四个字节写入此缓冲区的当前位置,然后将该位置增加四。

...

抛出:
BufferOverflowException - 如果此缓冲区中剩余的字节少于四个

要写入两个字节,请改用putShort...最好将counter 变量也更改为short,以明确预期的范围。

【讨论】:

  • 使用short可以工作,但是如果计数器达到128,转换后的字节将是-128而不是128
  • @Struct:这将是一组适当的位 - 只是 Java 中的 byte (不幸的是)已签名。 没有 byte 的值为 128。无论将两个字节的值转换回 short,都会得到正确的值。
【解决方案2】:

首先,您似乎假设 int 是大端。嗯,这是 Java,所以肯定会是这样。

其次,您的错误是意料之中的:一个 int 是 4 个字节。

由于您需要最后两个字节,因此无需通过字节缓冲区即可:

public static byte[] toBytes(final int counter)
{
    final byte[] ret = new byte[2];
    ret[0] = (byte) ((counter & 0xff00) >> 8);
    ret[1] = (byte) (counter & 0xff);
    return ret;
}

当然,您也可以使用ByteBuffer

public static byte[] toBytes(final int counter)
{
    // Integer.BYTES is there since Java 8
    final ByteBuffer buf = ByteBuffer.allocate(Integer.BYTES);
    buf.put(counter);
    final byte[] ret = new byte[2];
    // Skip the first two bytes, then put into the array
    buf.position(2);
    buf.put(ret);
    return ret;
}

【讨论】:

  • 在 ByteBuffer 示例中似乎有 2 个拼写错误:buf.put(counter) -> buf.putInt(counter); buf.put(ret) -> buf.get(ret);
【解决方案3】:

这应该可以工作

写入包含给定短值的两个字节,在 当前字节顺序,在当前位置进入这个缓冲区,然后 将位置增加 2。

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

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 2011-06-24
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    • 2010-11-08
    • 2014-05-04
    相关资源
    最近更新 更多