gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:24:09 25 4
gpt4 key购买 nike

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

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

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

这行吗:String s = new String(bytes);

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

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"

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

最佳答案

对于每个操作,您需要确定反向操作,而不仅仅是返回正确类型的任何操作。例如,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");

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

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

// 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 方法。

关于java - 将整数和字符串转换为字节数组,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21966063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com