我有一个计数器,从0计数到32767。
每一步,我想将计数器(int)转换为一个2字节数组。
我尝试过这个方法,但是我得到了一个BufferOverflowException异常:
byte[] bytearray = ByteBuffer.allocate(2).putInt(counter).array();
我有一个计数器,从0计数到32767。
每一步,我想将计数器(int)转换为一个2字节数组。
我尝试过这个方法,但是我得到了一个BufferOverflowException异常:
byte[] bytearray = ByteBuffer.allocate(2).putInt(counter).array();
int
在缓冲区中占用4个字节,无论其值如何。
ByteBuffer.putInt
清楚地说明了这一点和异常:BufferOverflowException
- 如果此缓冲区中剩余的字节数少于四个putShort
...并最好将您的counter
变量也更改为short
,以明确预期的范围。byte
是(不幸地)有符号的。不存在 byte
值为 128。无论如何将两个字节的值转换回 short
,都会得到正确的值。 - Jon Skeetpublic 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;
}
这应该可以工作
以当前字节顺序写入包含给定短整型值的两个字节到此缓冲区的当前位置,然后将位置增加两个。
byte[] bytearray = ByteBuffer.allocate(2).putShort((short)counter).array();