Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an int[] to byte[] in C#

I know how to do this the long way: by creating a byte array of the necessary size and using a for-loop to cast every element from the int array.

I was wondering if there was a faster way, as it seems that the method above would break if the int was bigger than an sbyte.

like image 534
soandos Avatar asked May 05 '11 11:05

soandos


People also ask

How do you divide bytes into integers?

We split the input integer (5000) into each byte by using the >> operator. The second operand represents the lowest bit index for each byte in the array. To obtain the 8 least significant bits for each byte, we & the result with 0xFF .

Can Char be converted to byte?

// ascii char to byte. Method 2: Using ToByte() Method: This method is a Convert class method. It is used to converts other base data types to a byte data type.


1 Answers

If you want a bitwise copy, i.e. get 4 bytes out of one int, then use Buffer.BlockCopy:

byte[] result = new byte[intArray.Length * sizeof(int)]; Buffer.BlockCopy(intArray, 0, result, 0, result.Length); 

Don't use Array.Copy, because it will try to convert and not just copy. See the remarks on the MSDN page for more info.

like image 167
Daniel Hilgarth Avatar answered Sep 21 '22 03:09

Daniel Hilgarth