stackMeUp
stackMeUp

Reputation: 552

Down casting an array of Int[] into an array of Byte[]

Is there a simple way to downcast an array of integers into an array of bytes?
Essentially, I would like to do the following thing (which does not work as is):

int[] myIntArray = new int[20];
byte[] byteArray = (byte[])myInArray;

The reason for doing this is that in my application myIntArray is actually a byte[], but was declared as an int[]. Meaning that only the least significant byte in myIntArray is of interest.

Upvotes: 0

Views: 1253

Answers (2)

Jamiec
Jamiec

Reputation: 136249

You might think this would work:

byte[] myByteArray = myIntArray.Cast<byte>().ToArray();

But it doesnt - see Why Enumerable.Cast raises an InvalidCastException?

You can use Select though to project to a new array.

byte[] myByteArray = myIntArray.Select(i => (byte)i).ToArray();

Live demo: https://rextester.com/KVR50332

Upvotes: 5

Antoine V
Antoine V

Reputation: 7204

Try using Linq Select

byte[] byteArray = myIntArray.Select(i=> (byte)i).ToArray();

Upvotes: 3

Related Questions