简体   繁体   English

在Java中分配给字节数组

[英]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() 第一个字节指定字符串的长度: (byte)string.length()
  • 2nd - Last bytes contain string data from string.getBytes() 2nd - 最后一个字节包含string.getBytes()字符串数据

Other than using a for loop, is there a quick way to initialize a byte array using bytes from two different variables? 除了使用for循环之外,还有一种使用来自两个不同变量的字节初始化字节数组的快捷方法吗?

You can use System.arrayCopy() to copy your bytes: 您可以使用System.arrayCopy()来复制您的字节:

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 :-) 虽然像其他人建议的那样使用像ByteArrayOutputStreamByteBuffer这样的东西可能是一种更清洁的方法,从长远来看对你来说会更好:-)

How about ByteBuffer ? 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: 虽然ByteBuffer通常是构建字节数组的最佳方法,但考虑到OP的目标,我认为以下内容将更加健壮:

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怎么样?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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