Problem
I need to convert two ints and a string of variable length to bytes.
What I've done
I converted each data type to an array of bytes, and then added them to the byte buffer. Of these, right after that, I will copy this buffer into a single byte array, as shown below.
byte[] nameByteArray = cityName.getBytes(); byte[] xByteArray = ByteBuffer.allocate(4).putInt(x).array(); byte[] yByteArray = ByteBuffer.allocate(4).putInt(y).array(); ByteBuffer byteBuffer = ByteBuffer.allocate(nameByteArray.length + xByteArray.length + yByteArray.length);
Now that seems a little redundant. I can, of course, put everything in a byte buffer and convert it to an array of bytes. However, I have no idea what string length is. So, how would I allocate a byte buffer in this case? (to allocate a byte buffer you must specify its capacity)
darksky
source share