I have array of double in java and I need to convert into array of short. Any idea?
Asked
Active
Viewed 300 times
-2
-
You should provide more detail in your question, what problem are you facing, how do you want to handle values that are to large, rounding etc. – Joakim Danielson Feb 17 '21 at 08:15
-
@JoakimDanielson . I have to play the array using audio track and it accepts short – Amanpal Singh Feb 17 '21 at 08:24
-
You may get a different value for any number beyond the max and min value a `short` variable can hold. Check https://stackoverflow.com/q/18860817/10819573 to understand it. – Arvind Kumar Avinash Feb 17 '21 at 08:37
-
That wasn't much of a clarification. – Joakim Danielson Feb 17 '21 at 10:06
2 Answers
2
double[] d = { 2, 3.2, 4.8, 123456789.123 };
short[] s = new short[d.length];
for (int i = 0; i < d.length; i++) {
s[i] = (short) d[i];
}
System.out.println("short output: " + Arrays.toString(s));
---------------------
Result: short output: [2, 3, 4, -13035]
Is that really what you need? Is the precision loss not important for you?

a_local_nobody
- 7,947
- 5
- 29
- 51

Sergiu Grisciuc
- 36
- 1
- 2
0
How do you want to print it...? You can cast your double to a short when printing a single value from the array like this:
public class array {
public static void main(String[] args){
double [] array = new double[] {132.45612, 9556.456789876, 6513.987652, 123456789.123};
System.out.println((short)array[3]);
}
}
This outputs -13035
By changing the number in the sysout, you should get a different result.

mhvejs
- 3
- 8