Video in progress
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()orslice()does not inherit the order: it isBIG_ENDIANagain. Setorderagain on every new buffer; DataInputStream.readInt()has no setting. For little-endian useInteger.reverseBytes(in.readInt()), or read the data into aByteBuffer;- Java has no unsigned types. If the format has
uint32, useInteger.toUnsignedLong(buf.getInt()), and foruint16useShort.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.
Sign up to mark studied questions and save your progress.