(java) Writing in file little endian

╄→гoц情女王★ 提交于 2019-12-20 17:36:50

问题


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?


回答1:


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();     



回答2:


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);
}



回答3:


Check out ByteBuffer, specifically the 'order' method. ByteBuffer is a blessing for those of us who need to interface with anything not Java.



来源:https://stackoverflow.com/questions/1394735/java-writing-in-file-little-endian

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!