I have a byte array I want to assign as follows:
- First byte specifies the length of the string:
(byte)string.length()
- 2nd - Last bytes contain string data from
string.getBytes()
Other than using a for loo开发者_如何转开发p, is there a quick way to initialize a byte array using bytes from two different variables?
You can use System.arrayCopy()
to copy your bytes:
String x = "xx";
byte[] out = new byte[x.getBytes().length()+1];
out[0] = (byte) (0xFF & x.getBytes().length());
System.arraycopy(x.getBytes(), 0, out, 1, x.length());
Though using something like a ByteArrayOutputStream
or a ByteBuffer
like other people suggested is probably a cleaner approach and will be better for your in the long run :-)
How about ByteBuffer
?
Example :
ByteBuffer bb = ByteBuffer.allocate(string.getBytes().length +1 );
bb.put((byte) string.length());
bb.put(string.getBytes());
While ByteBuffer
is generally the best way to build up byte arrays, given the OP's goals I think the following will be more robust:
public static void main(String[] argv)
throws Exception
{
String s = "any string up to 64k long";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bos);
out.writeUTF(s);
out.close();
byte[] bytes = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
DataInputStream in = new DataInputStream(bis);
String s2 = in.readUTF();
}
How about ByteArrayOutputStream
?
精彩评论