简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM