DataOutputStream: scrittura low byte first

3

3470816911

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
 
J

John B. Matthews

In a recent article, I understood (e-mail address removed) 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)>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top