开发者

Assigning to a byte array in Java

开发者 https://www.devze.com 2023-02-03 11:11 出处:网络
I have a byte array I want to assign as follows: First byte specifies the length of the string: (byte)string.length()

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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号