jean chu
jean chu

Reputation: 145

Converting BitArray to Byte

I have a code that converts BitArray values to byte[] values. I got the code also from stackoverflow.

The code is working great, I just don't understand one part.

When the codes copies the BitArray to Byte using BitArray.CopyTo() the byte reading is in LSB order.

Can someone help me understand why the converted byte is in LSB order?

strBit (is a string value that consists of 1/0)
byte[] myByte = new byte[50];

List<string> list = Enumerable.Range(0, strBit.Length / 8)
    .Select(i => strBit.Substring(i * 8, 8))
    .ToList();

for (int x = 0; x < list.Count; x++)
{
    BitArray myBitArray = new BitArray(list[x].ToString().Select(c => c == '1').ToArray());
    myBitArray.CopyTo(myByte, x);
}

Example Output:

  strBit[0] = 10001111  (BitArray)

when converted to Byte:

  myByte[0] = 11110001 (Byte) (241/F1)

Upvotes: 1

Views: 693

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Because we count bits from the right and items from the left; for instance for

 BitArray myBitArray = new BitArray(new byte[] { 10 });

We have for the byte 10 (counting from the right):

 10 = 00001010 (binary)
            ^
            second bit (which is 1)

when items of the corresponding array we count from the left:

 {false, true, false, true, false, false, false, false}
           ^
           corresponding second BitArray item (which is true)

That's why if we want to have an array of byte back we have to Reverse each byte representation, e.g. Linq solution

  using System.Collections;
  using System.Linq;

  ...

  BitArray myBitArray = ...

  byte[] myByte = myBitArray
    .OfType<bool>()
    .Select((value, index) => new { // into chunks of size 8
       value,
       chunk = index / 8 })
    .GroupBy(item => item.chunk, item => item.value)
    .Select(chunk => chunk // Each byte representation
      .Reverse()           // should be reversed   
      .Aggregate(0, (s, bit) => (s << 1) | (bit ? 1 : 0)))
    .Select(item => (byte) item)
    .ToArray();

Upvotes: 1

Related Questions