I am looking for the most efficient way to convert array of int
to array of byte
and vice versa.
I want to write a huge number of int
array and String to files so I can read them efficiently. I think the best way to save space and decrease reading time is to store them as byte
. Am I right?
I read the following link but is there any better way?
Convert integer into byte array (Java)
integers to bytes
I don't think there is a much better or more effective way then directly shifting the bytes/bits.
You will probably need to loop over the toBytes(..) method mentioned in the question you linked:
byte[] toBytes(int i)
{
byte[] result = new byte[4];
result[0] = (byte) (i >> 24);
result[1] = (byte) (i >> 16);
result[2] = (byte) (i >> 8);
result[3] = (byte) (i /*>> 0*/);
return result;
}
Like this:
for (int i = 0; i < integers.length; i++)
{
bytes[i] = toBytes(integers[i]);
}
bytes to integers
For bytes to integers you can do simple multiplication and adding which would probably be the fastest. Something like:
for (int i = 0; i < integers.length; i++)
{
integers[i] = ((int) (bytes[i] << 24)) + ((int) (bytes[i+1] << 16)) + ((int) (bytes[i + 2] << 8)) + ((int) (bytes[i + 3]));
}
Also see
Java integer to byte array
Byte Array and Int conversion in Java
converting bytes to int in Java
Fastest way to write an array of integers to a file in Java?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With