简体   繁体   English

保存字节数组中字节数组的长度

[英]Save length of byte array in a Byte array

I am writing in a BufferedOutputStream three times: 我在BufferedOutputStream中写了三次:

b1 = baos1.toByteArray();  
b2 = baos2.toByteArray();  

bos.write(b1);
bos.write(b2);
bos.write(b1.length);

System.out.println(b1.length);
System.out.println(b2.length);

bos.flush();
bos.close();

The I want to get the value wrote (b1.length) in another class but the value I get is different from the first *.println(). 我想在另一个类中获取值write(b1.length),但是我获得的值与第一个* .println()不同。

System.out.println(aux.length); // The entire stream (b1+b2+b1.length)
System.out.println(aux[aux.length - 1]);

For example: 例如:

Println 1 --> 123744 Println 1 - > 123744

Println 2 --> 53858 Println 2 - > 53858

Println 3 --> 177603 Println 3 - > 177603

Println 4 --> 96 Println 4 - > 96

In that case println1 and println4 should return the same size. 在这种情况下,println1和println4应该返回相同的大小。 What I am doing wrong? 我做错了什么?

I have checked that 1 byte is wrote (177603-123744-53858 = 1) that is the b1.length byte. 我已经检查了写入的1字节(177603-123744-53858 = 1),即b1.length字节。

Can someone help me to write correctly the size of the first byte array? 有人可以帮我正确写出第一个字节数组的大小吗?

A single byte in Java is a signed value with range -128..127 . Java中的单个byte是带符号的值,范围为-128..127 This is not enough for the value you are trying to store. 这对于您尝试存储的值是不够的。

You should write at least a 4 bytes integer to manage lengths up to Integer.MAX_VALUE . 您应该至少写入4个字节的整数来管理长度为Integer.MAX_VALUE长度。

What happens is that the value gets truncated to 1 byte, this is easy to see as 会发生什么,该值被截断为1个字节,这很容易看出来

123744 == 0x1E360
0x1E360 & 0xFF == 0x60
0x60 = 96

I have solved the issue doing this: 我已经解决了这个问题:

bos.write(ByteBuffer.allocate(4).putInt(b2.length).array());

instead of: 代替:

bos.write(b1.length);

Now it works and I can retrieve the length. 现在它工作,我可以检索长度。

在DataOutputStream中包装BufferedOutputStream并使用其write(byte[])writeInt(int)方法。

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

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