0

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!

Machavity
  • 30,841
  • 27
  • 92
  • 100
BarryLib
  • 299
  • 1
  • 5
  • 20

1 Answers1

2

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();

Aleks Andreev
  • 7,016
  • 8
  • 29
  • 37
  • Thanks for your reply. Your code seems not meet the needs. For example, when my bits[] are`1 1 0 0 0 0 0 0` I want the result be `3` not `192` – BarryLib Jul 16 '17 at 10:01