1

How do I change the typecast of an array of floats into an array of shorts with a one-to-one correspondence? i.e.

int bufferSize = 256;
short[] myShort = new short[bufferSize];
float[] myFloat = new float[bufferSize];
for(int i=0;i<bufferSize;i++){
     myShort[i] = (short) myFloat[i];
 }

I'm looking for a more compact, simpler code. I'm really short on processing time (no pun intended).

  • Of course, one might observe that in the above case you don't need to copy anything, since both arrays will be inited to zeros. But presumably you intend for there to be some added code that will modify myFloat after it's created and before it's "cast" to myShort. – Hot Licks May 07 '14 at 03:15

2 Answers2

4

I would leave it as is. There is no other way in Java standard library to do this.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
-2

If performance is the most important, I suggest using JNI(Java Native Interface).

Shortly, write this function in C/C++, and invoke it using native method.

the cast from float to short uses 2 JVM instructions: f2i, i2s, that will use many assembly instructions. Using native method, you can do this very fast using special cpu instruction(SSE?).

here is discussion on float to integer conversion.

Community
  • 1
  • 1
Xing Fei
  • 287
  • 1
  • 6
  • why downvote? I don't understand. He said ` really short on processing time`. Using C/C++, you can get acceleration from CPU or GPU, although I don't know how to. – Xing Fei May 07 '14 at 03:07