java - How to store and read a String out of a fixed-length byte array? -
i have byte array of fixed length, , want store string in it. like:
byte[] dst = new byte[512]; string foo = "foo"; byte[] src = foo.getbytes("utf-8"); (int = 0; < src.length; i++) { dst[i] = src[i]; }
but when want read string value out of dst, there's no way know string terminates (guess there's no notion of null terminators in java?). have store length of string in byte array, read out separately know how many bytes read byte array?
1. length
+payload
scenario
if need store string bytes custom-length array, can use first 1 or 2 bytes notion of "length".
the code 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 can check array, until find 0
element. there's no guarantee first 0
-element find 1 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 go length
+payload
scenario.
Comments
Post a Comment