Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Java floats to C

I have a java program using objects containing huge arrays of floats. Thing is for optimization reasons, I need to convert part of this code into C.

For benchmarking, I already converted the desired method in C. Thing is instead of taking objects as inputs, it now takes those float arrays.

I saved those arrays in files in Java, in order to easily access it from my C code. Problem is, Java floats and C floats are apparently completely different, and I get dummy values in my C code.

I did not find any source on the internet that could help me in this task. I did find this, but it is for C++ and I don't have access to those classes.

Would you have any suggestions? I could develop some kind of converter I guess, but It may take some time and there is probably a better solution online.

Thx,

EDIT :

I am saving the float array using a DataOutputStream and its writeFloat method.

like image 473
jlengrand Avatar asked Oct 10 '12 06:10

jlengrand


2 Answers

I would use JavaCL or JavaCV to use the GPU directly.

Note: these libraries work with Intel/AMD CPUs as well so you don't need to use the GPU if its not faster.

BTW: float in Java and C is the same. However if you use ObejctOutputStream this can only be read by Java and if you use DataOutputStream the data will be in Big Endian format. If you have an Intel/AMD CPU which is little endian you have to swap the bytes around.

If you use ByteBuffer and NIO to write the data you can make it big endian or little endian. The later requires no translation.

Note: you can access a float[] or FloatBuffer via JNI meaning it doesn't need to be written to a file.

To use FloatBuffer I suggest

FloatBuffer fb = ByteBuffer.allocateDirect(size*4)
                           .order(ByteOrder.nativeOrder())
                           .asFloatBuffer();
like image 116
Peter Lawrey Avatar answered Oct 05 '22 00:10

Peter Lawrey


First, you can run Java programs on GPU without converting to C: project RootBeer.

Second, Java floats are the same as C floats. The trick is to write and read them correctly. I recommend to use FileChannel and ByteBuffer which have methods to read and write floats. Pay attention to byte order, ByteBuffer have methods to set desired order.

like image 24
Alexei Kaigorodov Avatar answered Oct 04 '22 23:10

Alexei Kaigorodov