简体   繁体   中英

Assigning to a byte array in Java

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 loop, 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();
}

ByteArrayOutputStream怎么样?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM