(java) 在文件小端写入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1394735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
(java) Writing in file little endian
提问by Tony Stark
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):
我正在尝试编写 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)
Would write:
会写:
0c00 0301 0300 0100 0000 0100 0000
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?
我知道如何让写入方法占用正确的字节数(writeInt、writeChar 等),但我不知道如何让它以小端写入。有人知道吗?
回答by xap4o
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();
回答by ZZ Coder
ByteBuffer is apparently the better choice. You can also write some convenience functions like this,
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);
}
回答by Chris Arguin
Check out ByteBuffer, specifically the 'order' method. ByteBuffer is a blessing for those of us who need to interface with anything not Java.
查看ByteBuffer,特别是 ' order' 方法。ByteBuffer 对于我们这些需要与 Java 以外的任何东西进行交互的人来说是一个福音。

