Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

DataOutputStream: scrittura low byte first

49 views
Skip to first unread message

34708...@vodafone.it

unread,
Sep 15, 2008, 6:32:50 AM9/15/08
to
Salve,
uso il metodo writeInt() su un'istanza di DataOutputStream e noto che
mi scrive su file l'intero con modalità high byte first. Vorrei
avvenisse il contrario, cioè:

..
FileOutputStream fileOut = new FileOutputStream(nomeFileOut);
DataOutputStream out = new DataOutputStream (fileOut);
out.writeInt(1);
..

Vorei in fileOut avessi:

01 00
e non
00 01.


Come posso fare? E' configurabile in qualche modo il DataOutputStream?

Grazie mille

John B. Matthews

unread,
Sep 15, 2008, 12:25:24 PM9/15/08
to
In a recent article, I understood 34708...@vodafone.it to ask:

> Hi,
>
> [I used] the method writeInt () on an instance of DataOutputStream,
> and [it wrote] to [a] file with the high byte first. I want [it] to
> happen the opposite [way], namely:
>
> FileOutputStream fileOut = new FileOutputStream (nomeFileOut);

> DataOutputStream out = new DataOutputStream (fileOut);
> out.writeInt (1);
>

> [My] fileOut had:
> [00 00 00 01]
> and not
> [01 00 00 00].
>
> How can I somehow [configure] the DataOutputStream?
>
> Thank you very much.

ByteOrder.BIG_ENDIAN is the default. In a recent article, Mark Space
suggested using java.nio.ByteBuffer, as it "has methods for writing all
types of primitives as well as control over endianness."

<http://groups.google.com/group/comp.lang.java.help/msg/755517035cd44190?
hl=en>

<code>
import java.io.*;
import java.nio.*;
public class Order {
public static void main(String[] args) throws IOException {
int value = 0xCAFEBABE;


DataOutputStream out = new DataOutputStream (

new FileOutputStream("tempB.bin"));
out.writeInt(value);
out.close();

out = new DataOutputStream (
new FileOutputStream("tempL.bin"));
ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE/8);
bb.putInt(value);
bb.order(ByteOrder.LITTLE_ENDIAN);
out.writeInt(bb.getInt(0));
out.close();
}
}
</code>

<console>
$ javac Order.java ; java Order ; hd tempB.bin ; hd tempL.bin
000000: ca fe ba be ....
000000: be ba fe ca ....
</console>

<http://java.sun.com/javase/6/docs/api/java/nio/ByteBuffer.html#order(jav
a.nio.ByteOrder)>

--
John B. Matthews
trashgod at gmail dot com
home dot woh dot rr dot com slash jbmatthews

0 new messages