C# convert from uint[] to byte[]

后端 未结 5 1983
[愿得一人]
[愿得一人] 2021-01-13 20:35

This might be a simple one, but I can\'t seem to find an easy way to do it. I need to save an array of 84 uint\'s into an SQL database\'s BINARY field. So I\'m using the fol

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-13 20:50

    There is no built-in conversion function to do this. Because of the way arrays work, a whole new array will need to be allocated and its values filled-in. You will probably just have to write that yourself. You can use the System.BitConverter.GetBytes(uint) function to do some of the work, and then copy the resulting values into the final byte[].

    Here's a function that will do the conversion in little-endian format:

        private static byte[] ConvertUInt32ArrayToByteArray(uint[] value)
        {
            const int bytesPerUInt32 = 4;
            byte[] result = new byte[value.Length * bytesPerUInt32];
            for (int index = 0; index < value.Length; index++)
            {
                byte[] partialResult = System.BitConverter.GetBytes(value[index]);
                for (int indexTwo = 0; indexTwo < partialResult.Length; indexTwo++)
                    result[index * bytesPerUInt32 + indexTwo] = partialResult[indexTwo];
            }
            return result;
        }
    

提交回复
热议问题