Connecting Tech Pros Worldwide Help | Site Map

big endian vs little endian data

Dave Eland
Guest
 
Posts: n/a
#1: Jul 18 '05
It appears that the data I/O methods for the RandomAccessFile class
(e.g. readInt() and writeInt()) handle data in "big endian format"
(most significant byte first). If you have a file where the data was
written in "little endian format" (least significant byte first" how
is the best way to read that data in Java?

Dave Eland
daveland@oru.edu
A J Gage
Guest
 
Posts: n/a
#2: Jul 18 '05

re: big endian vs little endian data


Dave Eland <daveland@oru.edu> wrote in message news:<rhc1i053utmlo58n8ab2brg5heo5q5l6nt@4ax.com>. ..[color=blue]
> It appears that the data I/O methods for the RandomAccessFile class
> (e.g. readInt() and writeInt()) handle data in "big endian format"
> (most significant byte first). If you have a file where the data was
> written in "little endian format" (least significant byte first" how
> is the best way to read that data in Java?
>
> Dave Eland
> daveland@oru.edu[/color]

OK, if your reading ints, pullout each int and reverse the bytes.

int i = input_stream.readInt();
i = ((i & 0x000000ff) << 24) + ((i & 0x0000ff00) << 8) +
((i & 0x00ff0000) >>> 8) + ((i & 0xff000000) >>> 24);


Hope this helps.

AJG
A. W. Dunstan
Guest
 
Posts: n/a
#3: Jul 18 '05

re: big endian vs little endian data


Dave Eland wrote:
[color=blue]
> It appears that the data I/O methods for the RandomAccessFile class
> (e.g. readInt() and writeInt()) handle data in "big endian format"
> (most significant byte first). If you have a file where the data was
> written in "little endian format" (least significant byte first" how
> is the best way to read that data in Java?
>
> Dave Eland
> daveland@oru.edu[/color]

Look at ByteBuffer & company. Something like this:

RandomAccessFile file = new RandomAccessFile(filename, "r");
byte[] recordBuffer = new byte[RECORD_LENGTH];
ByteBuffer record = ByteBuffer.wrap(recordBuffer);
record.order(ByteOrder.BIG_ENDIAN);
FloatBuffer floatRecordBuffer = record.asFloatBuffer();
IntBuffer intRecordBuffer = record.asIntBuffer();

Use

file.seek(offset);
file.read(recordBuffer);

to read the file, and

intRecordBuffer.rewind();
intRecordBuffer.get(arrayOfInts, offset, sizeOfArray);

to get it into your arrayOfInts.



Closed Thread