Copying C# BitArray to byte[] produces incorrect result

37 Views Asked by At

As mentioned in the title, when I copy a BitArray to a byte array, the resulting byte array contains the correct values but in the wrong order.

So here is a small snippet of code I created that demonstrates the issue:

BitArray bits = new BitArray(new bool[] {   false,false,true,false,false,true,false,false,
                                                    true,false,false,true,false,false,true,false,
                                                    false,true,false,false,true,false,false,true,
                                                    false,true,true,false,true,true,false,true,
                                                    true,false,true,true,false,true,true,false,
                                                    true,true,false,true,true,false,true,true,
                                                    false,false,true,false,false,true,false,false,
                                                    true,false,false,true,false,false,true,false,
                                                    false,true,false,false,true,false,false,true,});

byte[] bytes = new byte[bits.Length / 8];
bits.CopyTo(bytes, 0);

foreach ( byte b in bytes )
    Console.WriteLine(b);

From my understanding, printing these byte values should give the results written below. Based on the fact that each byte is a value derived from the corresponding 8 bits in the BitArray.

  1. 00100100 = 36
  2. 10010010 = 146
  3. 01001001 = 73
  4. 01101101 = 109
  5. 10110110 = 182
  6. 11011011 = 219
  7. 00100100 = 36
  8. 10010010 = 146
  9. 01001001 = 73

However, these results are not the ones output in my code. Instead, I get the same byte values but in a different, seemingly arbitrary order:

output

Does anyone know why this is the case or alternatively another efficient way to convert a BitArray object to an array of bytes?

0

There are 0 best solutions below