Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...