将int和字符串转换为字节数组,反之亦然

时间:2014-02-23 08:43:46

标签: java arrays string int byte

我想将一些整数和一些字符串转换为单字节数组然后再返回。我已经对如何进行转换做了一些研究,但我不确定它是否正确。

将字符串转换为字节数组很容易:
byte[] bytes = string.getBytes();

通过Arrays.toString()再次将其转换回来,因为这只会创建一个字节字符串。

这是否有效:String s = new String(bytes);

将int转换为字节数组是这样的:

int[] data = { int1, int2, int3 }; 
ByteBuffer byteBuffer = ByteBuffer.allocate(data.length * 4);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(data);
byte[] my_app_state = byteBuffer.array();

但我不知道如何将其转换回来。

我的目标是说4个整数和2个字符串转换为单个字节数组,然后再将它们转换回来。

例如。我有这些对象,并希望它们转换为相同的字节数组。

int int1 = 1;
int int2 = 2;
int int3 = 3;
int int4 = 4;
String s1 = "mystring1"
String s2 = "mystring2"

更新:删除了我认为存在问题的代码。没有。

3 个答案:

答案 0 :(得分:3)

对于每个操作,您需要确定反向操作,而不仅仅是返回正确类型的任何操作。例如,即使类型正确,n * 2的反面也是m / 2而不是m - 2

Arrays.toString("Hi".getBytes()) => "{ 72, 105 }"

所以你可以做到

text.getBytes() => new String(bytes) // if the same character encoding is used.

更好的选择是

text.getBytes("UTF-8") => new String(bytes, "UTF-8");

数组的问题是你有两条信息a length和一些bytes如果你只是写字节,你不再知道长度,所以你不能轻易解码它(也许是不可能的)

在您的情况下,最简单的选择是使用数据流

// buffer which grows as needed.
ByteArrayOutputStream boas = new ByteArrayOutputStream();
// supports basic data types
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(data.length);
for(int i: data) dow.writeInt(i);
// write the length of the string + the UTF-8 encoding of the text.
dos.writeUTF(s1);
dos.writeUTF(s2);
byte[] bytes = bytes.toByteArray();

要执行相反的操作,请使用InputStream和readXxxx而不是writeXxxx方法。

答案 1 :(得分:1)

Java实现这一点非常简单,因为这是一个非常常见的用例。你需要什么看起来非常像序列化。

序列化的工作方式如下:单个对象可以转换为一组字节并存储在字节数组中(通常用于写入文件或通过网络发送)。

好处是任何对象都可以通过实现标记接口(只需1行代码)来实现序列化。此外,所有Wrapper数据类型以及像ArrayList这样的String和Collections对象都是可序列化的。

提出您的问题:将您的所有数据放在一个对象中并序列化该对象。我想到了3个选项: 1.一个Object []或ArrayList(如果你知道订单肯定,那么你可以根据位置访问) 2. HashMap,(如果你可以为每个人分配名称而不是依赖于位置) 3.使用int1,int2或更有意义的名称等字段创建自己的数据类型。 (您的类应该实现Serializable)。

现在,您的所有数据都会添加到单个对象中。将这一个对象转换为字节数组,您的工作就完成了。

检查此链接以了解如何将单个对象转换为字节数组: Java Serializable Object to Byte Array

    Object[] payload = new Object[]{int1, int2, int3, int4, string1, string2};
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(out);
    os.writeObject(payload);
    byte[] result = out.toByteArray(); //Done

答案 2 :(得分:0)

对于商店字符串,你必须使用像

这样的东西
IntBuffer intBuffer = byteBuffer.asIntBuffer();
CharBuffer stringBuffer = byteBuffer.asCharBuffer();

然后你必须遍历char[][] string = {s1.toCharArray(),s2.toCharArray()};上的循环 把每个字符放在stringBuffer中你需要做的更多事情就是让你的byteBuffer足以保存这些值我的朋友

相关问题