C# unsafe value type array to byte array conversions

后端 未结 7 802
梦毁少年i
梦毁少年i 2020-11-30 08:20

I use an extension method to convert float arrays into byte arrays:

public static unsafe byte[] ToByteArray(this float[] floatArray, int count)
{
    int arr         


        
7条回答
  •  庸人自扰
    2020-11-30 08:39

    I've written something similar for quick conversion between arrays. It's basically an ugly proof-of-concept more than a handsome solution. ;)

    public static TDest[] ConvertArray(TSource[] source)
        where TSource : struct
        where TDest : struct {
    
        if (source == null)
            throw new ArgumentNullException("source");
    
            var sourceType = typeof(TSource);
            var destType = typeof(TDest);
    
            if (sourceType == typeof(char) || destType == typeof(char))
                throw new NotSupportedException(
                    "Can not convert from/to a char array. Char is special " +
                    "in a somewhat unknown way (like enums can't be based on " +
                    "char either), and Marshal.SizeOf returns 1 even when the " +
                    "values held by a char can be above 255."
                );
    
            var sourceByteSize = Buffer.ByteLength(source);
            var destTypeSize = Marshal.SizeOf(destType);
            if (sourceByteSize % destTypeSize != 0)
                throw new Exception(
                    "The source array is " + sourceByteSize + " bytes, which can " +
                    "not be transfered to chunks of " + destTypeSize + ", the size " +
                    "of type " + typeof(TDest).Name + ". Change destination type or " +
                    "pad the source array with additional values."
                );
    
            var destCount = sourceByteSize / destTypeSize;
            var destArray = new TDest[destCount];
    
            Buffer.BlockCopy(source, 0, destArray, 0, sourceByteSize);
    
            return destArray;
        }
    }
    

提交回复
热议问题