Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BitArray returns bits the wrong way around?

This code:

BitArray bits = new BitArray(new byte[] { 7 });
foreach (bool bit in bits)
{
    Console.WriteLine(bit ? 1 : 0);
}

Gives me the following output:

11100000

Shouldn't it be the other way around? Like this:

00000111

I am aware that there is little and big endian, although those terms only refer to the position of bytes. As far as I know, they don't affect bits.

like image 415
haiyyu Avatar asked Jan 30 '12 16:01

haiyyu


2 Answers

The documentation for BitArray states:

The first byte in the array represents bits 0 through 7, the second byte represents bits 8 through 15, and so on. The Least Significant Bit of each byte represents the lowest index value: " bytes [0] & 1" represents bit 0, " bytes [0] & 2" represents bit 1, " bytes [0] & 4" represents bit 2, and so on.

When indexing bits, the convention is to start at the least significant end, which is the right side when written in binary notation. However, when enumerating the array, you start at index 0, so they are printed out left-to-right instead of right-to-left. That's why it looks backwards.

For example, the word 01011010 00101101 (90 45) would be indexed as:

 0  1  0  1  1  0  1  0  -  0  0  1  0  1  1  0  1
-----------------------    -----------------------
15 14 13 12 11 10  9  8     7  6  5  4  3  2  1  0

And you would pass it to the constructor as new byte[] { 45, 90 } since you pass it least-significant first. When printed out, it would display in index order as: 1011010001011010, which is the reverse of the original binary notation.

like image 70
Tadmas Avatar answered Sep 19 '22 16:09

Tadmas


The documentation is not explicit about it, but I guess the iterator iterates from the LSB to the MSB. Sound reasonable to me (personally!), unless you are printing out the bits. I had a look at BitArray.GetEnumerator Method.

like image 21
Matthias Meid Avatar answered Sep 18 '22 16:09

Matthias Meid