Reputation: 111
I'm trying to following up this tutorial about reading altitude from srtm-data. At the end I have to read 2 bytes from a file, which are big-endian and have to convert them to an integer in java.
File file = new File(filename);
InputStream inputStream = new FileInputStream(file);
long length = file.length();
byte[] bytes = new byte[(int) length];
inputStream.read(bytes);
inputStream.close();
byte[] byteArr = new byte[2];
byteArr[0] = bytes[pos];
byteArr[1] = bytes[pos+1];
int height = ByteBuffer.wrap(byteArr).order(ByteOrder.BIG_ENDIAN).getInt();
The problem is I'm getting an
java.nio.BufferUnderflowException
because java is expecting more bytes. How can I convert these two bytes to an integer?
Upvotes: 0
Views: 2344
Reputation: 2469
An integer is comprised of 4 bytes, so your byteArr needs to have 4 elements, not 2:
byte[] byteArr = new byte[4];
Upvotes: 1