Save length of byte array in a Byte array

380 views Asked by At

I am writing in a BufferedOutputStream three times:

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().

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 2 --> 53858

Println 3 --> 177603

Println 4 --> 96

In that case println1 and println4 should return the same size. What I am doing wrong?

I have checked that 1 byte is wrote (177603-123744-53858 = 1) that is the b1.length byte.

Can someone help me to write correctly the size of the first byte array?

3

There are 3 answers

0
Jack On

A single byte in Java is a signed value with range -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.

What happens is that the value gets truncated to 1 byte, this is easy to see as

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

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.

0
Evgeniy Dorofeev On

Wrap BufferedOutputStream in DataOutputStream and use its write(byte[]) and writeInt(int) methods.