C# convert from uint[] to byte[]

后端 未结 5 2048
[愿得一人]
[愿得一人] 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:53

    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;
    

提交回复
热议问题