在 Java 中分配给字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4619182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:14:38  来源:igfitidea点击:

Assigning to a byte array in Java

javaarraysvariable-assignment

提问by fredley

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()
  • 第一个字节指定字符串的长度: (byte)string.length()
  • 第二个 - 最后一个字节包含来自 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 循环之外,是否有使用来自两个不同变量的字节来初始化字节数组的快速方法?

回答by Guss

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 ByteArrayOutputStreamor a ByteBufferlike other people suggested is probably a cleaner approach and will be better for your in the long run :-)

尽管使用其他人建议的类似 aByteArrayOutputStreamByteBuffer类似的方法可能是一种更清洁的方法,并且从长远来看对您更好:-)

回答by Anon

While ByteBufferis 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();
}

回答by Jigar Joshi

How about ByteBuffer?

怎么样ByteBuffer

Example :

例子 :

    ByteBuffer bb = ByteBuffer.allocate(string.getBytes().length +1 );
    bb.put((byte) string.length());
    bb.put(string.getBytes());

回答by Brian Topping