Reputation: 55
what is the easiest way to convert an integer or a long value to a byte buffer?
example:
input : 325647187
output : {0x13,0x68,0xfb,0x53}
I have tried a ByteBuffer like this :
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putLong(325647187);
byte[] x=buffer.array();
for(int i=0;i<x.length;i++)
{
System.out.println(x[i]);
}
but I get exception
Exception in thread "main" java.nio.BufferOverflowException
at java.nio.Buffer.nextPutIndex(Buffer.java:527)
at java.nio.HeapByteBuffer.putLong(HeapByteBuffer.java:423)
at MainApp.main(MainApp.java:11)
Upvotes: 1
Views: 740
Reputation: 94
you can try this for an easier way of converting:
so you have 325647187 as your input, we can then have something like this
byte[] bytes = ByteBuffer.allocate(4).putInt(325647187).array();
for (byte b : bytes)
{
System.out.format("0x%x ", b);
}
for me this is(if not the most) an efficient way of converting to byte buffer.
Upvotes: 0
Reputation: 394156
You allocated a 4 bytes buffer, but when calling putLong
, you attempted to put 8 bytes in it. Hence the overflow. Calling ByteBuffer.allocate(8)
will prevent the exception.
Alternately, if the encoded number is an integer (as in your snippet), it's enough to allocate 4 bytes and call putInt()
.
Upvotes: 6