我有一个运行良好的 Python 代码,但我需要将它转换成 Java:
file_path = ...
with open(file_path, "rb") as file:
in = file.read(4 * 128 * 128)
numbers = struct.unpack('f' * 128 * 128, in)
我在这里找到其他类型的实现但我正在寻找 struct.unpack 在 Java 中的实现float type(C Type = f).
FloatBuffer
中。
var fis = new FileInputStream("/path/to/file");
var bytes = fis.readNBytes(4 * 128 * 128);
var floats = ByteBuffer.wrap(bytes)
// optionally, specify the byte order here
// .order(ByteOrder.LITTLE_ENDIAN)
.asFloatBuffer();
然后,您可以使用
floats.get(n)
获取索引 n
处的浮点数,或者 floats.put(n, f)
将浮点数 f
写入索引 n
,就像使用 float[]
一样。
如果你因为某些原因想要一个
float[]
,你需要分配一个新的并将floats
的内容读入其中:
var floatArray = new float[128 * 128];
floats.get(floatArray);