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.
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.
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.
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
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.
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