Search code examples
c#bitarray

Why I use new BitArray(byte[]), Can't get right bits


byte[] test = new byte[] {36, 146};

BitArray ba = new BitArray(test);

for(int i = 0; i < ba.Length; i++)
  Debug.Log(ba[i]);

I want get bits is :

False False True False False True False False True False False True False False True False

but return is:

False False True False False True False False False True False False True False False True

Why???


Solution

  • Let's try some different numbers, say 1 and 7 and let's have a different output:

     byte[] test = new byte[] {1, 7};
    
     BitArray ba = new BitArray(test);
    
     StringBuilder sb = new StringBuilder();
    
     for (int i = 0; i < ba.Length; i++) {
       if (i > 0 && i % 8 == 0)
         sb.Append(' ');
    
       sb.Append(ba[i] ? '1' : '0');
     }
    
     Console.Write(sb.ToString());
    

    Outcome:

     10000000 11100000
    

    Can you see what's going on?

       1 -> 0b00000001 -> 10000000 -> True False False False False False False False
       7 -> 0b00000111 -> 11100000 -> True  True  True False False False False False
    

    Let's return to initial values: 36, 146

      36 -> 0b00100100 -> 00100100 -> False False  True False False  True False False
     146 -> 0b10010010 -> 01001001 -> False  True False False  True False False  True 
    

    When we put 1 in binary the 1st bit the rightmost: 00000001, however when we represent the same 1 as a bit array we have the 1st bit leftmost: [1, 0, 0, 0, 0, 0, 0, 0] == [True, False, False, False, False, False, False, False].

    Unfortunately, 36 is a binary palindrome 00100100 it reads equaly from left to right and from right to left, which I think is the cause of the surprised behaviour (why first 8 bits are correct when last 8 are not).