Nice discussion, but you forgot to answer the person's question.
That's because the original question didn't make sense. The format the OP
specified they wanted was neither big nor little endian. I asked for
clarification, got none, so moved on.
"read the API docs" isn't exactly a helpful answer. I have read
through them and it seems like most of the internet and am still
having trouble.
That answer wasn't addressed to the OP.
Can anyone give me a little help on how to switch short, int, float
from short endian to big endian?
I am reading a DataInputStream, but the data is coming in "backward"
and java isn't outputting the value in the way I would like.
This is one way:
Read the data into a byte array.
Create a ByteBuffer and set its order to LITTLE_ENDIAN.
Wrap the ByteBuffer around the byte array.
Read the data from the ByteBuffer.
The above approach is most useful if you are reading complex data structures,
for example scientific data, where you typically read a complete "record" in a
single operation. Once you've read the "record" into the byte array you can
then extract the relevant data fields via the ByteBuffer.
This is code extracted from a class which reads little-endian data from a file:
this.file = new File( filename );
// get an InputStream on the file
in = new FileInputStream( file );
// get a DataInputStream which can be used to read words.
// if it's gzipped wrap it in a ZipInputStream
if ( fileName.endsWith( ".gz" ) )
dataIn = new DataInputStream( new GZIPInputStream( in ) );
else
dataIn = new DataInputStream( in );
.... some time later
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();
.... and later still
bufferArray = new byte[fitRecordLength];
dataBuffer = ByteBuffer.wrap( bufferArray );
dataBuffer.order( ByteOrder.LITTLE_ENDIAN );
dataIn.readFully( bufferArray );
dataBuffer.position( 0 );
int recordNumber = dataBuffer.getInt();
int r_time = dataBuffer.getInt();
etc.