Reputation: 189
What is the actual length of a byte array? For example:
int x = 123 equals to byte[] b = 0111 1011
Now if I want to figure out the length of said integer I would use b.length
, but from what I gather, length can be only multiples of 8 because every byte represents a mandatory number. Is that the case with byte array or am I missing something?
Upvotes: 3
Views: 15092
Reputation: 50010
from what I gather, length can be only multiples of 8
I think you're a little confused between bits and bytes. A byte is 8 bits. The .length
of a byte array is its length in bytes, which is always a whole number of bytes, which is a multiple of 8 bits.
An int in memory is always 4 bytes, which is 32 bits. Your example int 123 has the following bit representation:
0000 0000 0000 0000 0000 0000 0111 1011
A byte array can be any whole number of bytes long, so b.length
is whatever size you create it as. It does not need to be a whole number of ints long, but if you want to convert between ints and byte arrays, it is simpler if you always store whole ints. That means, make those byte arrays a multiple of 4 bytes long.
If you simply want to know the length of a number written in binary, the easiest way is to convert it to a string and measure its length. The method Integer.numberOfLeadingZeros
might also be useful to you.
int x = 123;
System.out.println(Integer.toBinaryString(x)); // 1111011
System.out.println(Integer.toBinaryString(x).length()); // 7
System.out.println(x == 0 ? 1 : (32 - Integer.numberOfLeadingZeros(x))); // 7
Upvotes: 6
Reputation: 48404
You can have byte
arrays that do not represent the bytes in an integer value.
As such, their length (inferred by getting the length
public field of the array) is totally arbitrary.
Upvotes: 1