Video in progress

Strong Middle 📁 IO and NIO

A number read with `getInt()` from a binary file written by another system comes out strangely large. What could be going on?

ByteBuffer is big-endian by default. If the file was written in little-endian (C/C++ on x86, .NET, many binary formats), the bytes are read in reverse. You need to set buf.order(ByteOrder.LITTLE_ENDIAN); DataInputStream reads big-endian only.

📖 Answer

An example: the file wrote the number 1 in little-endian: 01 00 00 00. Java reads it as big-endian and gets 0x01000000 = 16,777,216.

ByteBuffer buf = ByteBuffer.wrap(header);
int wrong = buf.getInt(0);                    // 16777216

buf.order(ByteOrder.LITTLE_ENDIAN);
int right = buf.getInt(0);                    // 1

A few subtle points:

  • a new buffer made with duplicate() or slice() does not inherit the order: it is BIG_ENDIAN again. Set order again on every new buffer;
  • DataInputStream.readInt() has no setting. For little-endian use Integer.reverseBytes(in.readInt()), or read the data into a ByteBuffer;
  • Java has no unsigned types. If the format has uint32, use Integer.toUnsignedLong(buf.getInt()), and for uint16 use Short.toUnsignedInt(buf.getShort()). Otherwise large values come out negative.

Network protocols are usually big-endian ("network byte order"), so this problem is rare in socket code. In file formats (BMP, WAV, ZIP headers, many game and sensor files), little-endian is common.

To check: look at the first bytes with xxd -l 16 file.bin and compare with the expected value. If a small number shows up at the start as 01 00 00 00, it is little-endian.