2

I need to convert an int[] array to a ushort[] array in order to use the method Array.Copy() from theses two types of array.

Which method should I use ?

PLB
  • 197
  • 1
  • 10
  • 5
    A loop is an accepted method to iterate over arrays or lists. I doubt there is a pre-made implementation for this, since you will need to deal with values of `int` that do not fit into a `ushort`. So you need to implement error handling. As long as you have only primitive types, you'll automatically have a copy of the data, so potentially, you don't even need `Array.Copy()`. – Thomas Weller May 19 '20 at 08:43

3 Answers3

4
var arr = Array.ConvertAll(inputs, val => checked((ushort)val));

The advantage of Array.ConvertAll here is that it right-sizes the target array from the outset, so it never allocates multiple arrays, and can be used conveniently.

The checked here causes the int to ushort conversion to throw an exception if an overflow is detected; this is not done by default.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

The simple way to get a ushort array from an int array is:

public static void Main(string[] args)
    {
        int[] intArr = new int[5]{1,2,3,4,5}; // Creates an array of ints 
        ushort[] ushortArr = new ushort[5];   // Creates an array of ushorts

        // Copy the int array to the ushort array
        for(int i=0; i<intArr.Length; i++){
            ushortArr[i] = (ushort)intArr[i];
        }

        // Prints the ushort array
        foreach(ushort u in ushortArr){
            Console.Write(u+", ");
        }
    }

The output of this program is:

1, 2, 3, 4, 5,

note: you need to make sure that the length of the ushort array is the same as the length of the int array.

I believe this is a very simple solution. I hope it helps :)

omri klein
  • 146
  • 6
  • 1
    If you say `new int[]{1,2,3,4,5};`, the compiler will figure out the length for you, and if you say `new ushort[intArr.Length];`, then it will automatically get the correct length, no matter how you change the content of `intArr`. – Corak May 19 '20 at 09:06
1

There are cleaner alternatives, but assuming you need to do somethng when an int can't be an unsigned short:

    public ushort[] ToUnsignedShortArray(int[] intArray)
    {
        if (intArray == null)
        {
            return new ushort[0];
        }

        var shortArray = new ushort[intArray.Length];
        for (var i = 0; i < intArray.Length; i++)
        {
            // add your logic for determining what to do if the value can't be an unsigned short
            shortArray[i] = (ushort)intArray[i];
        }

        return shortArray;
    }
Joe Ratzer
  • 18,176
  • 3
  • 37
  • 51