Reputation: 552
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
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