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!

3
  • Are you asking how to convert int to ushort? Any code attempts you can share? Commented Jul 14, 2017 at 10:30
  • bits array are not a c# type perhaps you mean byte ? or System.Collections.BitArray ? Commented Jul 14, 2017 at 10:32
  • sorry for my expression, I reedited my question. Commented Jul 14, 2017 at 11:51

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply. Your code seems not meet the needs. For example, when my bits[] are1 1 0 0 0 0 0 0 I want the result be 3 not 192

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.