askeet
askeet

Reputation: 719

How convert System.Byte[] To System.UInt64[]?

I try converting any C# object to System.UInt64[].

System.Byte[] to System.UInt64[].
double[] to System.UInt64[].
int[] to System.UInt64[].

Example, convert object f1, f2 to ulong b[]

 object f1 = new Byte[3] { 1, 2, 3 };  
 ulong b[]  = Convert<ulong>(f1); //---  ?

 object f2 = new double[3] { 1, 2, 3 };  
 b  = Convert<ulong>(f2); //---  ?

Output

b[0] = 1
b[1] = 2
b[3] = 3

tell me how to write the function code Convert<T>(object value), where T output type value ulong ?

restrictions: Framework 2.0, input type can be obtained from the object f.

It turned out the only way to make

 ulong[] b = Array.ConvertAll((byte[])f, element => Convert.ToUInt64(element));

Unfortunately input type is not necessarily be byte []

Upvotes: 0

Views: 487

Answers (3)

abto
abto

Reputation: 1628

Use a linq expression:

System.Byte[] source = new System.Byte[] { 1, 2, 3 };
// does not work: System.UInt64[] target = source.Cast<System.UInt64>().ToArray();
System.UInt64[] target = source.Select(b => (System.UInt64)b).ToArray();

This works for all datatypes in source which can be casted to 'System.UInt64'.

Edit: As Thomas Levesque pointed out Cast<System.UInt64>()does not work here, so we must use a Select(ConvertFunction) here.

Upvotes: 1

askeet
askeet

Reputation: 719

Solved the problem with this, but maybe there are better decisions

    static T[] MyConvert<T>(object value){
        T[] ret = null;
        if (value is Array)
        {
            Array arr = value as Array;
            ret = new T[arr.Length];
            for (int i = 0 ; i < arr.Length; i++ )
            {
                ret[i] =  (T)Convert.ChangeType(arr.GetValue(i), typeof(T));.
            }
        }
        return ret;
    }

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292535

You can use Array.ConvertAll:

byte[] bytes = new byte[3] { 1, 2, 3 };
ulong[] ulongs = Array.ConvertAll<byte, ulong>(b => (ulong)b);

Upvotes: 0

Related Questions