In Java, a byte
is 8 bits, while an int
is 32 bits.
To convert each of your int
s to a single byte
without loss of data, you need to ensure all your numbers are in the range -128 to 127 inclusive.
If they are in this range, then you should just store them as bytes in the first place (if this is not possible, there are ways to do the conversion already discussed).
If they are not in this range, then you shouldn't be converting them to bytes at all because it will force your numbers into the range, and thus you will lose a lot of data.
Alternatively, you could use short
, as that would be 16 bits (giving you the range -32,768 to 32,767 inclusive).
But if you can't ensure that your numbers will be within these ranges, then you will need to use int
.
Note: You can store each int
as 4 byte
s or as 2 short
s, but each number would still be 32 bits, so you're not gaining any space efficiency by doing so.
You can read more about Java's primitive types here.