Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int[] array to short[] array in Java

Tags:

java

arrays

I have an int array for which i have allocated space for 100 elements. There is another array inShort[]. How can I convert inInt[] to inShort[]?

Is it necessary to allocate new memory for inShort[] or there is a way through which I can cast to inInt[]?

int inInt[] = new int[100];
short inShort[];
like image 866
Rog Matthews Avatar asked Dec 10 '22 01:12

Rog Matthews


1 Answers

short inShort[] = new short[100];

for(int i = 0; i < 100; i++)
{
    inShort[i] = (short)inInt[i];
}

However, you are very likely to overflow the short if the int is outside the range of the short (i.e. less than -32,768 or greater than 32,767). It's actually really easy to overflow the short, since an int ranges from -2,147,483,648 to 2,147,483,647.

like image 91
Kiril Avatar answered Jan 03 '23 21:01

Kiril