C # convert from uint [] to byte []

It may be simple, but I cannot find an easy way to do this. I need to save an array of 84 uint in the BINARY field of an SQL database. Therefore, I use the following lines in a C # ASP.NET project:

//This is what I have uint[] uintArray; //I need to convert from uint[] to byte[] byte[] byteArray = ??? cmd.Parameters.Add("@myBindaryData", SqlDbType.Binary).Value = byteArray; 

So how do you convert from uint [] to byte []?

+4
source share
5 answers

What about:

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

This will do what you want in little-endian format ...

+10
source

You can use System.Buffer.BlockCopy for 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 bytes from the first array to the second.

To convert back, just do the same thing in reverse order.

+4
source

There is no built-in conversion function for this. Due to how the arrays work, it will be necessary to allocate a whole new array and fill in its values. You probably just have to write it yourself. You can use the System.BitConverter.GetBytes(uint) function to do some of the work, and then copy the resulting values ​​to the final byte[] .

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

Follow @ liho1eye's advice, make sure your uints really fit in bytes, otherwise you are losing data.

+2
source

If you need all the bits from each uint, you will need to make a byte of the appropriate size [] and copy each uint into the four bytes that it represents.

Something like this should 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; 
0
source

Source: https://habr.com/ru/post/1379935/


All Articles