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
.
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 .
// 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With