Re: DataOutputStream: scrittura low byte first
In a recent article, I understood 3470816911@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