ByteBuffer and Byte Array

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)

+7
source share
3 answers

Since you cannot put a string in ByteBuffer directly, you always need to convert it to an array of bytes first. And if you have it in the form of an array of bytes, you know its length.

Therefore, the optimized version should look like this:

 byte[] nameByteArray = cityName.getBytes(); ByteBuffer byteBuffer = ByteBuffer.allocate(nameByteArray.length + 8); byteBuffer.put(nameByteArray); byteBuffer.putInt(x); byteBuffer.putInt(y); 
+8
source

Assuming you want everything in one byte buffer, why can't you do the following

 ByteBuffer byteBuffer = ByteBuffer.allocate( cityName.getBytes().length+ 4+ 4); byteBuffer.put(cityName.getBytes()).putInt(x).putInt(y); 
+4
source

If you do not limit the maximum length of a string, you always need to dynamically calculate the number of bytes needed to store the string. If you limit the string to the maximum length, you can pre-calculate the maximum number of bytes to store any string and allocate the appropriate ByteBuffer size. Although this is not required for the simple example you specified, you might want to keep the byte length of the string as well as the string. Then, when reading data, you know how many bytes make up your string.

+1
source

All Articles