Reputation: 39691
I have a byte array of a fixed length, and I want to store a String in it. Something like:
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];
}
But when I want to read the string value back out of dst, there's no way to know where the string terminates (guess there's no notion of null terminators in java?). Do I have to store the length of the string in the byte array, read it out separately to know how many bytes to read from the byte array?
Upvotes: 4
Views: 9189
Reputation: 785266
I would suggest using ByteArrayOutputStream
for holding the data and length of data. A simple example:
ByteArrayOutputStream dst = new ByteArrayOutputStream();
String foo = "foo";
byte[] src = foo.getBytes("utf-8");
dst.write(src.length); // write length
dst.write(src); // write data
TESTING:
byte[] tmp = dst.toByteArray(); // length+data
byte[] newsrc = new byte[tmp[0]]; // tmp[0] is length
System.arraycopy(tmp, 1, newsrc, 0, tmp[0]); // copy data without length
System.out.println("Result str => " + new String(newsrc, "utf-8")); // create String again
//=> Result str => foo
PS: This is a simple example, for real data handling it would be better to reserve 2 or more bytes for holding the length of the data you're storing.
Upvotes: 0
Reputation: 18320
You can encode your string with Modified UTF-8 encoding. This way you can use 0 as terminator.
But, if possible, you should stick to more straightforward approach.
Upvotes: 0
Reputation: 4907
1. length
+payload
scenario
If you need to store string bytes into custom-length array, then you can use first 1 or 2 bytes for the notion of "length".
The code would look like:
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
element scenario
Or you can check the array, until you find a 0
element. But there's no guarantee that the first 0
-element you find is the one you need.
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;
}
My choice:
I would personally go with length
+payload
scenario.
Upvotes: 7