(java)写入文件小端序

2022-09-02 19:30:16

我正在尝试编写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等),但我不知道如何让它以小字节序写入。有人知道吗?


答案 1

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

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显然是更好的选择。你也可以写一些方便的函数,像这样,

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

推荐