Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Byte Array to an Int Array

I am reading a file by using:

int len = (int)(new File(args[0]).length());
    FileInputStream fis =
        new FileInputStream(args[0]);
    byte buf[] = new byte[len];
    fis.read(buf);

As I found here. Is it possible to convert byte array buf to an Int Array ? Is converting the Byte Array to Int Array will take significantly more space ?

Edit: my file contains millions of ints like,

100000000 200000000 ..... (written using normal int file wirte). I read it to byte buffer. Now I want to wrap it into IntBuffer array. How to do that ? I dont want to convert each byte to int.

like image 453
alessandro Avatar asked Jul 11 '12 16:07

alessandro


People also ask

Can we convert byte to int in java?

The intValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as int.

How do I convert an integer to a byte array?

When you want to convert an int value to a byte array, you can use the static method ByteArray. toByteArray(). This method takes an int input and returns a byte array representation of the number.

How do you convert a byte array into a String?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.


1 Answers

You've said in the comments that you want four bytes from the input array to correspond to one integer on the output array, so that works out nicely.

Depends on whether you expect the bytes to be in big-endian or little-endian order, but...

 IntBuffer intBuf =
   ByteBuffer.wrap(byteArray)
     .order(ByteOrder.BIG_ENDIAN)
     .asIntBuffer();
 int[] array = new int[intBuf.remaining()];
 intBuf.get(array);

Done, in three lines.

like image 88
Louis Wasserman Avatar answered Oct 08 '22 00:10

Louis Wasserman