1

Given a read only collection of ints, how do I convert it to a byte array?

ReadOnlyCollection<int> collection = new List<int> { 118,48,46,56,46,50 }.AsReadOnly(); //v0.8.2

What will an elegant way to convert 'collection' to byte[] ?

Rotem Varon
  • 1,597
  • 1
  • 15
  • 32
  • Yes, 0 to 225. I plan to use the bitConverter to convert it to string. As for the endiannass, can be both. – Rotem Varon Mar 22 '18 at 06:00
  • Possible duplicate of [C# int byte conversion](https://stackoverflow.com/questions/3641274/c-sharp-int-byte-conversion) – mjwills Mar 22 '18 at 06:01

1 Answers1

4

You can use LINQ's Select method to cast each element from int to byte. This will give you an IEnumerable<byte>. You can then use the ToArray() extension method to convert this to a byte[].

collection.Select(i => (byte)i).ToArray();

If you don't want to use LINQ then you can instantiate the array and use a for loop to iterate over the collection instead, assigning each value in the array.

var byteArray = new byte[collection.Count];

for (var i = 0; i < collection.Count; i++)
{
    byteArray[i] = (byte)collection[i];
}
Alex Wiese
  • 8,142
  • 6
  • 42
  • 71