-   Programming (
-   -   How to binary-write in Java in little endian? (

kornerr 12-10-2006 01:53 AM

How to binary-write in Java in little endian?
Now I use:

File file = new File ("__smth__");
            try {
                FileOutputStream file_out = new FileOutputStream (file);
                DataOutputStream out = new DataOutputStream (file_out);
                out.writeInt (123);
                //out.writeFloat (3.14159f);
                file_out.close ();
            catch (IOException ex) {
                System.out.println ("IO exception: " + ex);

But it's in Big Endian! I need it in Little Endian. Can anyone give me an example of binary-writing an int to a file in little endian?

paulsm4 12-10-2006 02:10 AM

Java deliberately insulates you from whether the underlying platform is big-endian or little endian. In general, this is a Good Thing.

This article explains how you can "bit-twiddle" values to one byte order or the other:

result = ((a<<24) | (b<<16) | (c<< 8) | d);// big endian
result = ( a | (b<<8) | (c<<16) | (d<<24) ); // little endian

the article also gives you a helper class, BinaryFile, that might be just what you're looking for:

'Hope that helps .. PSM

kornerr 12-10-2006 02:25 AM

No, it's not what I wanted :)
I want an example with binary-writing with setByteOrder method.

pasteNoctem 12-11-2006 09:16 AM

I don't know what the term Endian means... but RandomAccessFiles are like writing in binary..

I don't think I was of any help, but..

kornerr 12-11-2006 10:38 AM

I found what I was looking for:

public void save (String fn) {
        try {
            ByteBuffer buf = ByteBuffer.allocate (1048576); // 1 MiB
            buf.order (ByteOrder.LITTLE_ENDIAN);
            buf.putInt (123);
            buf.putFloat (3.14159);
            buf.flip ();
            FileChannel out = new FileOutputStream (fn).getChannel ();
            out.write (buf);
            out.close ();
        catch (IOException e) {
            System.out.println ("I/O exception: " + e);

Thanks for help anyway ;)

paulsm4 12-11-2006 11:53 AM

pasteNoctem -

"Endian" refers to how a given CPU reads bytes in a word: left to right (like Motorola or SPARC processors) or right to left (like Intel x86 processors). Here's a good link:

kornerr -

The reason ByteOrder works is that you happen to be using Java "nio" (instead of, say, Readers, Writers or RandomAccess file types). If your application can easily use nio, great. Otherwise, you'll probably need a more general ("bit twiddling") solution.


pasteNoctem 12-12-2006 06:00 AM

Thanks for the info and the link..

Ware the RandomAccessFiles of any revelance or help???

All times are GMT -5. The time now is 01:30 PM.