Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am working on a C# application. I have a byte variable, i want to iterate over all bits of it.

byte var = 3;
System.Collections.BitArray bits = new System.Collections.BitArray(var);
Console.WriteLine("Length of collection : " + bits.Length);
for (int i = 0; i < bits.Length; i++)
{
    Console.WriteLine(bits[i]);
}

This code gives me the following output:

Length of collection : 3
False
False
False

But as the binary representation of 3 is 00000011 so i expect the following output

False
False
False
False
False
False
True
True

What am i doing wrong ? How can i achieve the required output

See Question&Answers more detail:os

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

1 Answer

You're calling the BitArray(int length) constructor:

Initializes a new instance of the BitArray class that can hold the specified number of bit values, which are initially set to false.

So you're creating a BitArray of length 3, not a BitArray which contains the bits from the integer value 3.

You want the BitArray(byte[] bytes) constructor:

Initializes a new instance of the BitArray class that contains bit values copied from the specified array of bytes.

byte var = 3;
BitArray bits = new BitArray(new byte[] { var });
Console.WriteLine("Length of collection : " + bits.Length);
for (int i = 0; i < bits.Length; i++)
{
    Console.WriteLine(bits[i]);
}

Outputs:

Length of collection : 8
True
True
False
False
False
False
False
False

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...