ByteBuffer和字节数组 [英] ByteBuffer and Byte Array

查看:76
本文介绍了ByteBuffer和字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

我需要将两个整数和一个可变长度的字符串转换为字节.

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

我做什么

我将每种数据类型转换为字节数组,然后将它们添加到字节缓冲区中.在那之后,我将把该缓冲区复制到一个字节数组,如下所示.

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)

推荐答案

由于不能将字符串直接放入ByteBuffer,因此始终必须首先将其转换为字节数组.而且,如果您以字节数组的形式拥有它,那么您就会知道它的长度.

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);

这篇关于ByteBuffer和字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆