Loading ...

How To Read Little Endian File Of Floats In Java

Hello everybody,

today I want to document another issue that took from me plenty of time. Recently I've used following code in Python in order to save array of numpy numbers:

import numpy as np

newImage = ...some way of getting array

np.ndarray.tofile(newImage, newFn)

But when I tried to get that content in Java code, I faced issue that my inputs where unreadable by Java. After spending some time over net I've found that Python uses little endian encoding, while Java uses another encoding for saving floats. 

So my research of little endian gave me the following code result in java for reading little endian:

InputStream inputStream = null;
DataInputStream dataInputStream = null;

dataInputStream = new DataInputStream(new FileInputStream(fileName));

LittleEndianDataInputStream lendian = new LittleEndianDataInputStream(dataInputStream);

List<Float> listOfFloats = new ArrayList<Float>();
Date before = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //Or whatever format fits best your needs.
//System.out.println("before reading file " + sdf.format(before));

int fileSize = x * y * z * sizeInt;

byte[] fileContent = new byte[fileSize];
lendian.readFully(fileContent);

ReadFromFile(listOfFloats, fileSize, fileContent);

And function ReadFromFile looks like this:

private static void ReadFromFile(List<Float> listOfFloats, int fileSize, byte[] fileContent) {
for(int i = 0; i < fileSize; i+=4)
{
int valueInt = (fileContent[i + 3]) << 24 |
(fileContent[i + 2] &0xff) << 16 |
(fileContent[i + 1] &0xff) << 8 |
(fileContent[i]&0xff);
float value = Float.intBitsToFloat(valueInt);
listOfFloats.add(value);
}
}