Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to convert array of int to array of byte and vice versa?

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)

like image 665
user3487667 Avatar asked Jan 10 '23 02:01

user3487667


2 Answers

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?

like image 178
flotothemoon Avatar answered Jan 17 '23 15:01

flotothemoon


In Java, a byte is 8 bits, while an int is 32 bits.

To convert each of your ints 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 bytes or as 2 shorts, 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.

like image 26
Luke Willis Avatar answered Jan 17 '23 15:01

Luke Willis