我有一个字节数组,想要按照以下方式进行赋值:
- 第一个字节指定字符串的长度:
(byte)string.length()
- 第二个到最后一个字节包含从
string.getBytes()
获取的字符串数据
除了使用for循环之外,是否有一种快速的方法可以使用来自两个不同变量的字节初始化字节数组?
我有一个字节数组,想要按照以下方式进行赋值:
(byte)string.length()
string.getBytes()
获取的字符串数据除了使用for循环之外,是否有一种快速的方法可以使用来自两个不同变量的字节初始化字节数组?
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());
虽然像其他人建议的使用ByteArrayOutputStream
或ByteBuffer
这样的东西可能是更清晰的方法,并且从长远来看会更好 :-)
(0xFF & ...)
操作是完全多余的。(byte)
强制转换以相同的方式截断。只有在返回整数时才需要关注。 - Mark Peters有关 ByteBuffer
的情况如何?
示例:
ByteBuffer bb = ByteBuffer.allocate(string.getBytes().length +1 );
bb.put((byte) string.length());
bb.put(string.getBytes());
String.getBytes()
变体。 - Anon虽然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();
}
int
时,它们将被扩展符号位。因此,您必须屏蔽扩展符号位以获取范围0..255:b&0xFF
- Anon