我有一个短[512x512]数组,需要使用 little endian 写入二进制文件。我知道如何写一个简短的 little endian 文件中。我认为可能存在更好的方法,而不是遍历数组逐一写入的方式

最佳答案

有点像这样:

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

10-08 20:07