Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(java) Writing in file little endian

I'm trying to write TIFF IFDs, and I'm looking for a simple way to do the following (this code obviously is wrong but it gets the idea across of what I want):

out.writeChar(12) (bytes 0-1)
out.writeChar(259) (bytes 2-3)
out.writeChar(3) (bytes 4-5)
out.writeInt(1) (bytes 6-9)
out.writeInt(1) (bytes 10-13)

Would write:

0c00 0301 0300 0100 0000 0100 0000

I know how to get the writing method to take up the correct number of bytes (writeInt, writeChar, etc) but I don't know how to get it to write in little endian. Anyone know?

like image 434
Tony Stark Avatar asked Sep 08 '09 15:09

Tony Stark


People also ask

Is Java little endian?

In Java, data is stored in big-endian format (also called network order). That is, all data is represented sequentially starting from the most significant bit to the least significant.

How to check endianness in Java?

Java is strictly big endian as far as I know. There's no way (and indeed no reason) to find out the endianness of the underlying architecture without invoking native code. I think you're out of luck. The JVM shields you from such implementation specific details.

Why Java uses big-endian?

Everything in Java binary files is stored in big-endian order. This is sometimes called network order. This means that if you use only Java, all files are done the same way on all platforms: Mac, PC, UNIX, etc. You can freely exchange binary data electronically without any concerns about endian-ness.

Is JVM big-endian?

A JVM can give the appearance of being big-endian from the POV of the bytecode it executes while still actually storing multi-byte values in native endianness.


2 Answers

Maybe you should try something like this:

ByteBuffer buffer = ByteBuffer.allocate(1000); 
buffer.order(ByteOrder.LITTLE_ENDIAN);         
buffer.putChar((char) 12);                     
buffer.putChar((char) 259);                    
buffer.putChar((char) 3);                      
buffer.putInt(1);                              
buffer.putInt(1);                              
byte[] bytes = buffer.array();     
like image 175
xap4o Avatar answered Oct 14 '22 09:10

xap4o


ByteBuffer is apparently the better choice. You can also write some convenience functions like this,

public static void writeShortLE(DataOutputStream out, short value) {
  out.writeByte(value & 0xFF);
  out.writeByte((value >> 8) & 0xFF);
}

public static void writeIntLE(DataOutputStream out, int value) {
  out.writeByte(value & 0xFF);
  out.writeByte((value >> 8) & 0xFF);
  out.writeByte((value >> 16) & 0xFF);
  out.writeByte((value >> 24) & 0xFF);
}
like image 38
ZZ Coder Avatar answered Oct 14 '22 11:10

ZZ Coder