(java)在文件little endian中编写

我正在尝试编写TIFF IFD,我正在寻找一种简单的方法来执行以下操作(这段代码显然是错误的,但它可以解决我想要的问题):

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) 

写道:

0c00 0301 0300 0100 0000 0100 0000

我知道如何让写入方法占用正确的字节数(writeInt,writeChar等),但我不知道如何让它以小端编写。 谁知道?

也许你应该尝试这样的事情:

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

ByteBuffer显然是更好的选择。 你也可以写一些像这样的便利函数,

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

查看ByteBuffer ,特别是’ order ‘方法。 对于我们这些需要与任何非Java接口的人来说,ByteBuffer是一种祝福。