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

1
  • Something like a ByteBuffer or a FloatBuffer seems possible here, depending on your requirements. Commented Apr 6, 2023 at 0:18

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

5 Comments

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 Could it be because of the endianness? What endianness does your python code use? Specify that using the order method I showed.
It worked after I took your advice using. order(ByteOrder.LITTLE_ENDIAN). Appreciated!
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 are you still reading 4*128*128 bytes? That will be 128*64 doubles, not 128*12&. Doubles take up twice as much space.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.