7/15 Is it possible through JNI to write a function which takes a float[]
array and through the magic of c casts it to an int array and then
returns the int array to Java, not modifying the actual data?
If not, is there a good Java way to do the C equivalent of:
int* i = (int*) f; ?
Don't ask whether I really need to be doing this because there is a
good (performance) reason.
\_ You can modify your implementation of VMFloat, or create a new
class similar to it, to provide an additional method that works
on arrays of ints and floats, rather than just on individual 32
bit values. This will entail creating a new shared library, etc.
This is probably the cleanest and most efficient way, but obviously
will not be portable. I am assuming you know how to write the
C necessary to convert the array type while leaving the bit
representation unchanged. -- ilyas
will not be portable. -- ilyas
\_ Do you know of any in-Java way to convert float[] to int[]
without using JNI or touching the underlying data? -op
\_ If you thought about it, you should be shocked if there were.
\_ I do not know of such a way. I think when you are starting to
care about performance to the extent where you don't want to
just call floatToIntBits on each element of the array, you
should either forget platform independence, or use a better
language. By the way, the previous poster is wrong, there
is no reason Java shouldn't provide this functionality in
VMFloat (it provides a function for individual 32 bit values).
It just doesn't because it sucks. -- ilyas
\_ Sure:
for(int i = 0; i < float_array.length; i++){
int_array[i] = java.lang.Float.floatToIntBits(float_array[i]);
}
If you want to avoid the overhead of a loop, or aren't
willing to write your own shared library + class wrapper to
do what this loop does in one swipe, or aren't willing to
abandon Java, then you lose. -- ilyas
\_ I'm already doing the above, but want to avoid an additional
O(n) step, and am too lazy to write another JNI wrapper.
I guess I do lose. I also saw ByteBuffer has methods for
providing IntBuffer and FloatBuffer views, but I can't find
a low overhead way to go FloatBuffer->ByteBuffer or
IntBuffer->ByteBuffer.
\_ For reference, consider how a well-implemented strongly
typed language (ocaml) handles this:
let float_array = [| 1.0; 2.0; 3.0 |] in
let int_array : Int32.t = Obj.magic float_array in
...
Obj.magic is an unconditional type cast without promotion.
-- ilyas |