# short [] <-> double[] conversion query

• 12-06-2010, 04:29 PM
KittenFace
short [] <-> double[] conversion query
I am using some example code to try and implement some Matlab capabilities in Java. One of the methods involves the conversion of a short[] to and from a double[].
Here is the code from the example
Code:

```        public ShortAndDouble(short[] array) {                 shortArray = array;                 doubleArray = new double[shortArray.length];                 for (int i = 0; i < shortArray.length; i++) {                         doubleArray[i] = (double)(shortArray[i]) / 32768;                 }         }```
Likewise, conversion back to Short[] simply * the double value by 32768
I am still new to this kind of thing, but wont this method loose some precision. Is there a more precise way to do the conversion?

Many thanks!
• 12-06-2010, 08:15 PM
Zack
Code:

```Converting from double to short: double d = 5.0; short s = (new Double(d)).shortValue(); Converting from short to double: short s = 5; double d = (new Short(s)).doubleValue();```
I'm not sure why you're dividing by 2^15, in all honesty... you could even just do a single cast from short to double. The short value 5 is equivalent to the double value of 5.0, not 0.000152587890625. Is your data encoded somehow in a specific range?
• 12-06-2010, 08:24 PM
Fillis52
This is example code from a basic implementation of DSP. I thought that the way it was done was hacky, but didnt know how to improve on it with the basic knowledge I have
• 12-06-2010, 08:30 PM
JosAH
Quote:

Originally Posted by Fillis52
This is example code from a basic implementation of DSP. I thought that the way it was done was hacky, but didnt know how to improve on it with the basic knowledge I have

Encoding doubles in the range [-1, 1) to shorts by scaling them as the OP showed is fine; you do lose some precision though because a double has 53 bits of precision in its mantissa while a short only stores 15 of them.

kind regards,

Jos