Reputation: 299
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
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