Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of bytes in byte array

I have an array byte[] arr;

ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] arr = out.toByteArray();

How can I measure the data size in arr (if it was written to disk or transferred via network)? Are below approaches are correct - they suppose that sizeof(byte) = 1B

int byteCount = out.size();
int byteMsgCount = arr.length;
like image 474
Yakov Avatar asked Dec 07 '22 22:12

Yakov


1 Answers

Yes, by definition the size of a variable of type byte is one byte. So the length of your array is indeed array.length bytes.

out.size() will give you the same value, i.e. the number of bytes that you wrote into the output stream.

[Edit] From cricket_007 comment: if you look at the implementation of size and toByteArray

public synchronized byte toByteArray()[] {
    return Arrays.copyOf(buf, count);
}

public synchronized int size() {
    return count;
}

... so toByteArray basically copies the current output buffer, up to count bytes. So using size is a better solution.

like image 85
christophetd Avatar answered Dec 10 '22 11:12

christophetd