KKKk
KKKk

Reputation: 93

Convert list<int[]> to byte[]

How to convert list<int[]> to byte[]?

I could use this:

 byte[] bytes = lista.SelectMany(BitConverter.GetBytes).ToArray();

But it works only for list<int>. If you have few ideas - most efficient is welcome.

Upvotes: 1

Views: 2382

Answers (5)

Bashn
Bashn

Reputation: 314

If you used the BitConverter on purpose you can use this (will output all 4 bytes of the integer separately)

byte[] buffer = testData.SelectMany(arr => arr.SelectMany(x => BitConverter.GetBytes(x))).ToArray();

for the sake of completeness:

List<int> reversed = Enumerable.Range(0, buffer.Length / 4)
                               .Select(x => BitConverter.ToInt32(buffer, x * 4))
                               .ToList();

As in Yacoub Massad's answer this will revers in a List<int> instead of List<int[]> because by flatten the List<int[]> first we lose the length informationen of the arrays.


If you only want to cast the int values to bytes you can use this

byte[] buffer = testData.SelectMany(arr => arr.Select(x => (byte)x)).ToArray();

Upvotes: 1

Yacoub Massad
Yacoub Massad

Reputation: 27871

How about this:

byte[] bytes =
    lista
    .SelectMany(x => x)
    .SelectMany(BitConverter.GetBytes)
    .ToArray();

UPDATE:

To convert the result to List<int>, you can do the following:

List<int> list =
    bytes
        .Select((item, index) => new {item, index})
        .GroupBy(x => x.index/4)
        .Select(g => g.Select(x => x.item).ToArray())
        .Select(x => BitConverter.ToInt32(x, 0))
        .ToList();

Upvotes: 5

Vlad Bezden
Vlad Bezden

Reputation: 89765

var result = lista.SelectMany(x => x.SelectMany(y => BitConverter.GetBytes(y))).ToArray();

Upvotes: 1

Yuriy A.
Yuriy A.

Reputation: 752

        var listOfIntArray = new List<int[]>
        {
            new[] {1, 2, 3},
            new[] {4, 5},
            new[] {6}
        };

        var listOfBytes = new List<byte>();

        foreach (var intArray in listOfIntArray)
        {
            var listOfByteArray = intArray.Select(BitConverter.GetBytes);

            foreach (var byteArray in listOfByteArray)
            {
                listOfBytes.AddRange(byteArray);
            }
        }

Upvotes: 1

Victor Viola
Victor Viola

Reputation: 585

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(list);
byte[] bytes = bos.toByteArray();

Upvotes: 0

Related Questions