简体   繁体   English

将int转换为byte时的BufferOverflowException

[英]BufferOverflowException while converting int to byte

I have an counter which counts from 0 to 32767 我有一个从0到32767的counter

At each step, I want to convert the counter (int) to an 2 byte array. 在每一步,我想将counter (int)转换为2字节数组。

I've tried this, but I got a BufferOverflowException exception: 我试过这个,但是我得到了一个BufferOverflowException异常:

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

Yes, this is because an int takes 4 bytes in a buffer, regardless of the value. 是的,这是因为无论值如何, int都会在缓冲区中占用4个字节。

ByteBuffer.putInt is clear about both this and the exception: ByteBuffer.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. 将包含给定int值的四个字节(按当前字节顺序)写入当前位置的此缓冲区,然后将位置增加4。

... ...

Throws: 抛出:
BufferOverflowException - If there are fewer than four bytes remaining in this buffer BufferOverflowException - 如果此缓冲区中剩余的字节少于四个

To write two bytes, use putShort instead... and ideally change your counter variable to be a short as well, to make it clear what the range is expected to be. 要写两个字节,请使用putShort ...并理想地将counter变量更改为short ,以明确预期范围。

First, you seem to assume that the int is big endian. 首先,您似乎假设int是大端。 Well, this is Java so it will certainly be the case. 嗯,这是Java所以肯定会是这样。

Second, your error is expected: an int is 4 bytes. 其次,您的错误是预期的:int是4个字节。

Since you want the two last bytes, you can do that without having to go through a byte buffer: 由于您需要最后两个字节,因此无需通过字节缓冲区即可:

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;
}

You could also use a ByteBuffer , of course: 你当然可以使用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;
}

This should work 这应该工作

Writes two bytes containing the given short value, in the current byte order, into this buffer at the current position, and then increments the position by two. 将当前字节顺序中包含给定short值的两个字节写入当前位置的此缓冲区,然后将位置递增2。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM