2

I have a Python code that works fine but I will need to convert it into Java:

    file_path = ...
    with open(file_path, "rb") as file:
        in = file.read(4 * 128 * 128)
        numbers = struct.unpack('f' * 128 * 128, in)

I found the implementation for other types here but I am looking for the implementation of the struct.unpack in Java for float type(C Type = f).

Ryan M
  • 18,333
  • 31
  • 67
  • 74
newbie5050
  • 51
  • 6

1 Answers1

1

You can wrap the bytes you read from the file in a 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();

Then, you can use floats.get(n) to get the float at index n, or floats.put(n, f) to write the float f into index n, just like you can with a float[].

If you want a float[] for some reason, you need to allocate a new one and read the contents of floats into it:

var floatArray = new float[128 * 128];
floats.get(floatArray);
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • I ran the above code and got different results from Python. I would expect to get these results like (18.477258682250977, 18.461912155151367, 18.826318740844727, 18.76152801513672,...) but I got these results from Java code: (8.107548E27, NaN, 3.28386592E8, -5.015591E-22, -5.2745868E-12, 2.7122066E24, 997716.06,...) – newbie5050 Apr 06 '23 at 14:26
  • @newbie5050 Could it be because of the endianness? What endianness does your python code use? Specify that using the `order` method I showed. – Sweeper Apr 06 '23 at 14:40
  • It worked after I took your advice using. order(ByteOrder.LITTLE_ENDIAN). Appreciated! – newbie5050 Apr 06 '23 at 16:47
  • I am trying to modify the above code into Double (for higher precision): var doubles = ByteBuffer.wrap(bytes) // optionally, specify the byte order here .order(ByteOrder.LITTLE_ENDIAN).asDoubleBuffer(); var doubleArray = new double[128 * 128]; doubles.get(doubleArray); but I got the error. Do you have an idea how to modify the code for double? – newbie5050 Apr 06 '23 at 17:31
  • @newbie5050 are you still reading 4*128*128 bytes? That will be 128*64 doubles, not 128*12&. Doubles take up twice as much space. – Sweeper Apr 06 '23 at 23:09