BarryLib
BarryLib

Reputation: 299

How to parse bits array to byte array in c#?

This question is very close to Bit array to Byte array in JAVA, I want to convert the following bit array to a byte array?

int[] bits = {1, 0, 1, 0, 1, 1, 0, 1, 0, 1};

But different to the answer is the relevant question, I want to store the result big-endian which should be:

0xB5 0x02

How I suppose to do this? Thanks!

Upvotes: 0

Views: 157

Answers (1)

Aleks Andreev
Aleks Andreev

Reputation: 7054

Try this code:

byte[] result = bits.Select((x, i) => new {byteId = i / 8, bitId = i % 8, bit = x})
    .GroupBy(x => x.byteId)
    .Select(x => (byte) x.Reverse().Aggregate(0, (t, n) => t | n.bit << n.bitId))
    .ToArray();

Upvotes: 2

Related Questions