sign in | join about | help | sitemap
Connecting Tech Pros Worldwide
Dave Eland's Avatar

big endian vs little endian data


Question posted by: Dave Eland (Guest) on July 18th, 2005 12:33 AM
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
Join Bytes!
2 Answers Posted
A J Gage's Avatar
Guest - n/a Posts
#2: 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
> Join Bytes![/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's Avatar
A. W. Dunstan July 18th, 2005 12:47 AM
Guest - n/a Posts
#3: 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
> Join Bytes![/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.



 
Not the answer you were looking for? Post your question . . .
196,829 members ready to help you find a solution.
Join Bytes.com

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over 196,829 network members.
Post your question now . . .
It's fast and it's free

Popular Articles

Top Community Contributors