3

我有一个short[512x512] 数组需要写入一个带有little endian的二进制文件。我知道如何用little endian写一个简短的文件。我认为可能有比逐个循环遍历数组更好的方法

4

2 回答 2

8

有点像这样:

short[] payload = {1,2,3,4,5,6,7,8,9,0};
ByteBuffer myByteBuffer = ByteBuffer.allocate(20);
myByteBuffer.order(ByteOrder.LITTLE_ENDIAN);

ShortBuffer myShortBuffer = myByteBuffer.asShortBuffer();
myShortBuffer.put(payload);

FileChannel out = new FileOutputStream("sample.bin").getChannel();
out.write(myByteBuffer);
out.close();

有点像这样把它拿回来:

ByteBuffer myByteBuffer = ByteBuffer.allocate(20);
myByteBuffer.order(ByteOrder.LITTLE_ENDIAN);
FileChannel in = new FileInputStream("sample.bin").getChannel();
in.read(myByteBuffer);
myByteBuffer.flip();
in.close(); // do not forget to close the channel

ShortBuffer myShortBuffer = myByteBuffer.asShortBuffer();
myShortBuffer.get(payload);
System.out.println(Arrays.toString(payload));
于 2012-05-08T21:09:04.723 回答
3

如果你真的需要这个快速,最好的解决方案是将短裤放入一个ByteBuffer小端字节顺序。然后,在一个操作中使用FileChannel.

使用方法设置ByteBuffer' 字节顺序.order()

于 2012-05-08T20:45:39.970 回答