I have an counter
which counts from 0 to 32767
At each step, I want to convert the counter
(int) to an 2 byte array.
I've tried this, but I got a BufferOverflowException
exception:
byte[] bytearray = ByteBuffer.allocate(2).putInt(counter).array();
Yes, this is because an int
takes 4 bytes in a buffer, regardless of the value.
ByteBuffer.putInt
is clear about both this and the 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
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.
First, you seem to assume that the int is big endian. Well, this is Java so it will certainly be the case.
Second, your error is expected: an int is 4 bytes.
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:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With