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

1. Member Join Date
Dec 2010
Posts
1
Rep Power
0

## 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
Java 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!  Reply With Quote

2. ## Java 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?  Reply With Quote

3. Member Join Date
Jul 2010
Posts
3
Rep Power
0

## 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  Reply With Quote

4. ##  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  Reply With Quote

array, double, short 