Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a list of ints to a byte array

I tried to use the List.ConvertAll method and failed. What I am trying to do is convert a List<Int32> to byte[]

I copped out and went this route, but I need to figure out the ConvertAll method...

List<Int32> integers...

internal byte[] GetBytes()
{
    List<byte> bytes = new List<byte>(integers.Count * sizeof(byte));
    foreach (Int32 integer in integers)
        bytes.AddRange(BitConverter.GetBytes(integer));

    return bytes.ToArray();
}
like image 373
MQS Avatar asked Jun 22 '10 23:06

MQS


1 Answers

Since you don't want a byte[][] where each integer maps to an array of four bytes, you cannot call ConvertAll. (ConvertAll cannot perform a one-to-many conversion)

Instead, you need to call the LINQ SelectMany method to flatten each byte array from GetBytes into a single byte[]:

integers.SelectMany(BitConverter.GetBytes).ToArray()
like image 85
SLaks Avatar answered Sep 24 '22 14:09

SLaks