How do I convert int [] to short []?
int[] iBuf = new int[2];
iBuf[0] = 1;
iBuf[1] = 2;
short[] sBuf = new short[2];
Buffer.BlockCopy(iBuf, 0, sBuf, 0, 2);
result
iBuf[0] = 1
sBuf[0] = 1
iBuf[1] = 2
sBuf[1] = 0
My desired result
iBuf[0] = 1
sBuf[0] = 1
iBuf[1] = 2
sBuf[1] = 2
The result is different from what I want.
Is there a way to convert without using loops?
+3
source to share
2 answers
You can use Array.ConvertAll method.
Example:
int[] iBuf = new int[2];
...
short[] sBuf = Array.ConvertAll(iBuf, input => (short) input);
This method takes an input array and a transformer and the result will be your desired array.
Edit: An even shorter option would be to use the existing Convert.ToInt16 method. inside ConvertAll:
int[] iBuf = new int[5];
short[] sBuf = Array.ConvertAll(iBuf, Convert.ToInt16);
So how does ConvertAll work? Let's take a look at the implementation:
public static TOutput[] ConvertAll<TInput, TOutput>(TInput[] array, Converter<TInput, TOutput> converter)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (converter == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter);
}
Contract.Ensures(Contract.Result<TOutput[]>() != null);
Contract.Ensures(Contract.Result<TOutput[]>().Length == array.Length);
Contract.EndContractBlock();
TOutput[] newArray = new TOutput[array.Length];
for (int i = 0; i < array.Length; i++)
{
newArray[i] = converter(array[i]);
}
return newArray;
}
To answer the real question ... no, at some point a loop will be involved to convert all values. You can program it yourself or use the methods already built.
+6
source to share
int is 32 bits long and short is 16 bits, so the way to copy the data won't work correctly.
A generic way would be to create a method to convert ints to shorts:
public IEnumerable<short> IntToShort(IEnumerable<int> iBuf)
{
foreach (var i in iBuf)
{
yield return (short)i;
}
}
and then use it:
int[] iBuf = new int[2];
iBuf[0] = 1;
iBuf[1] = 2;
short[] sBuf = IntToShort(iBuf).ToArray();
0
source to share