我有一个固定长度的字节数组,我想在其中存储一个字符串。像这样的东西:
byte[] dst = new byte[512];
String foo = "foo";
byte[] src = foo.getBytes("utf-8");
for (int i = 0; i < src.length; i++) {
dst[i] = src[i];
}
但是当我想从 dst 中读回字符串值时,无法知道字符串的终止位置(猜猜 java 中没有空终止符的概念?)。是不是要把字符串的长度存到字节数组里,单独读出来,就知道要从字节数组中读取多少字节了?
最佳答案
<强>1。 length
+payload
场景
如果您需要将字符串字节存储到自定义长度数组中,那么您可以使用前 1 或 2 个字节作为“长度”的概念。
代码如下:
byte[] dst = new byte[256];
String foo = "foo";
byte[] src = foo.getBytes("utf-8");
dst[0] = src.length;
System.arraycopy(src, 0, dst, 1, src.length);
<强>2。 0
元素场景
或者您可以检查数组,直到找到 0
元素。但不能保证您找到的第一个 0
元素就是您需要的元素。
byte[] dst = new byte[256];
String foo = "foo";
byte[] src = foo.getBytes("utf-8");
System.arraycopy(src, 0, dst, 0, src.length);
int length = findLength(dst);
private int findLength(byte[] strBytes) {
for(int i=0; i< dst.length; ++i) {
if (dst[i] == 0) {
return i;
}
}
return 0;
}
我的选择:
我个人会选择 length
+payload
场景。
关于java - 如何从固定长度的字节数组中存储和读取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18108607/