3
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???

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Aron
  • 61
  • 3
  • 2
    The bits are inserted in bit order, where least significant bit is bit 0 not bit 7. You don't notice this with 36 because in binary that is a palindrome. – Matthew Watson Jun 27 '19 at 09:46
  • `BitArray` stores bits as elements of array differently (first bit is least significant) than binary presentation which can easily lead to confusion. E.g. `1` is stored as `1000 0000` and `128` as `0000 0001`. – Sinatr Jun 27 '19 at 09:57

1 Answers1

1

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).

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    Thank you! 00100100 is read equaly from left to right and from right to left! HaHa – Aron Jun 28 '19 at 10:32