ByteBuffer and Byte Array

血红的双手。 提交于 2021-02-20 07:43:59

问题


Problem

I need to convert two ints and a string of variable length to bytes.

What I did

I converted each data type into a byte array and then added them into a byte buffer. Of which right after that I will copy that buffer to one 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 certainly place everything into byte buffer and convert that to a byte array. However, I have no idea what I string length is. So how would I allocate the byte buffer in this case? (to allocate a byte buffer you must specify its capacity)


回答1:


As you can not put a String into a ByteBuffer directly you always have to convert it to a byte array first. And if you have it in byte array form you know it's 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);



回答2:


Assuming that you want everything in one bytebuffer why can you not do the following

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



回答3:


Unless you restrict the maximum length of the string you will always need to dynamically calculate the number of bytes required to store the string. If you restrict the string to a maximum length then you can calculate ahead of time the maximum number of bytes to store any string and allocate an appropriate sized ByteBuffer. Although not required for the simple example you gave, you may want to consider storing the string byte length as well as the string. Then when reading back the data you know how many bytes make up your string.



来源:https://stackoverflow.com/questions/7257475/bytebuffer-and-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!