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[] ?
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];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.