Re: problems reading binary file
On Wed, 09 Jun 2010 10:14:29 +0000, Thomas Pornin wrote:
You _might_ correct your code by using Float.float.toRawIntBits()
instead of Float.floatToIntBits(), but even if it works, it is
non-robust (it assumes that DataInputStream also does things that way).
A more correct way of doing things is to read the bytes as an "int"
directly, which basically removes steps 2 and 3 altogether. This would
look like this:
System.out.print(Float.intBitsToFloat(swap(in.readInt())) + " ");
I prefer to load the data into a byte array, then use a ByteBuffer to
access the data directly from memory in the "correct" format. Everything
necessary is already available in the standard API classes, no manual bit
shifting, byte-swapping etc. is required.
The basic scenario is:
create a ByteBuffer
set it to ByteBuffer.LITTLE_ENDIAN
loop:
read block of data into byte[]
wrap ByteBuffer around byte[]
read data from ByteBuffer
E.g. this is an extract of some code which is run routinely here, and
reads little-endian data files:
DataInputStream dataIn;
short fitRecordLength;
short inxRecordLength;
....
// read the fit and inx lengths (this is little endian)
byte[] lengthBytes = new byte[4];
dataIn.readFully( lengthBytes );
// wrap the byte array in a ByteBuffer, this allows
// reading of little endian data
ByteBuffer bb = ByteBuffer.wrap( lengthBytes );
bb.order( ByteOrder.LITTLE_ENDIAN );
fitRecordLength = bb.getShort();
inxRecordLength = bb.getShort();
....
ByteBuffer dataBuffer;
byte[] bufferArray;
bufferArray = new byte[fitRecordLength];
dataBuffer = ByteBuffer.wrap( bufferArray );
dataBuffer.order( ByteOrder.LITTLE_ENDIAN );
dataIn.readFully( bufferArray );
dataBuffer.position( 0 );
int recordNumber = dataBuffer.getInt();
--
Nigel Wade