C# convert from uint[] to byte[]

徘徊边缘 提交于 2019-12-01 06:54:07

How about:

byte[] byteArray = uintArray.SelectMany(BitConverter.GetBytes).ToArray();

This'll do what you want, in little-endian format...

You can use System.Buffer.BlockCopy to do this:

byte[] byteArray = new byte[uintArray.Length * 4];
Buffer.BlockCopy(uintArray, 0, byteArray, 0, uintArray.Length * 4];

http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx

This will be much more efficient than using a for loop or some similar construct. It directly copies the bytes from the first array to the second.

To convert back just do the same thing in reverse.

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;
    }
byte[] byteArray = Array.ConvertAll<uint, byte>(
    uintArray,
    new Converter<uint, byte>(
        delegate(uint u) { return (byte)u; }
    ));

Heed advice from @liho1eye, make sure your uints really fit into bytes, otherwise you're losing data.

If you need all the bits from each uint, you're gonna to have to make an appropriately sized byte[] and copy each uint into the four bytes it represents.

Something like this ought to work:

uint[] uintArray;

//I need to convert from uint[] to byte[]
byte[] byteArray = new byte[uintArray.Length * sizeof(uint)];
for (int i = 0; i < uintArray.Length; i++)
{
    byte[] barray = System.BitConverter.GetBytes(uintArray[i]);
    for (int j = 0; j < barray.Length; j++)
    {
          byteArray[i * sizeof(uint) + j] = barray[j];
    }
}
cmd.Parameters.Add("@myBindaryData", SqlDbType.Binary).Value = byteArray;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!