Reading a C ++ binary in Java
I have a 500MB binary. with a bunch of floating point records. It was written by a C ++ program. I would load it in C ++ like this.
void load(char f_name[], int size, float data[])
{
std::fstream f_bin(f_name, std::ios::in|std::ios::binary);
f_bin.seekg(std::ios::beg);
f_bin.read((char*)data, size*sizeof(float));
f_bin.close();
}
float *data;
int size = 123456789;
data = new float[size];
load("myFile.bin", size, data);
And I can access the float values: data [x]; In C ++ it works preatty fast. Is there something in the java module?
Edit After reading a bit, I have this so far:
RandomAccessFile f = new RandomAccessFile("C://path//myFile.bin", "r");
byte[] bytes = new byte[(int)f.length()];
f.read(bytes);
float fl = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getFloat();
System.out.println(fl);
Which prints the floating point record first . Now I have to put float over float and put it in an array for example float[] data
.
source to share
You can do this in Java.
try(FileChannel fc = new RandomAccessFile("myFile.bin", "rw").getChannel()) {
FloatBuffer fb = fc.map(MapMode.READ_WRITE, 0, fc.size())
.order(ByteOrder.nativeOrder()).asFloatBuffer();
// use fb
}
It's pretty fast since memory maps to the file and avoids copying memory (you can do the same in C ++)
source to share
The Java standard is very precise about how floating points should be displayed:
Java Virtual Machine Specification 2.3.2: The floating point types are float and double, which are conceptually related to 32-bit single-precision and 64-bit double precision IEEE 754 values ββand operations specified in the IEEE standard for binary floating point arithmetic ( ANSI / IEEE Std. 754-1985, New York).
But the C ++ standard doesn't give many guarantees regarding this:
C ++ 11 standard 3.9.1 / 8: There are three floating point types: float, double and long double. The double type provides at least the same precision as float, and the double double type provides at least the same precision as double. (...) The representation of values ββof floating point types is implementation defined by strong>.
With, <limits>
you can figuratively learn a little more about your floats: std::numeric_limits<float>::is_iec559
for example, it will tell you if the IEC-559 / IEEE-754 standard is used (the same as java):
- If so, you can read the float using binary data as is. (Edit after PoweredByRice's comment, in fact you still have to deal with potential content issues because IEEE-754 leaves that point open. For more information on how to force ordering on the C ++ side, see here . On the java side, you can force byte ordering or use the default).
- If not, you will need to read the bytes and write floating point conversion programs, which is usually tricky.
source to share