user3216114
user3216114

Reputation: 325

BitArray AND operation

I have created one BitArray program.

private void Form1_Load(object sender, EventArgs e)
{
    BitArray bit1 = new BitArray(4);
    bit1[0] = true;
    bit1[1] = false;
    bit1[2] = true;
    bit1[3] = false;
    for (int a = 0; a < bit1.Count; a++)
    {
        listBox1.Items.Add(bit1[a]);
    }

    bool[] arr = new bool[] { false, true, true, false };
    BitArray bit2 = new BitArray(arr);
    for (int a = 0; a < bit2.Count; a++)
    {
        listBox2.Items.Add(bit2[a]);
    }

    BitArray bit3 = bit1.And(bit2);
    for (int a = 0; a < bit3.Count; a++)
    {
        listBox3.Items.Add(bit3[a]);
    }
    for (int a = 0; a < bit1.Count; a++)
    {
        listBox4.Items.Add(bit1[a]);
    }
    for (int a = 0; a < bit2.Count; a++)
    {
        listBox5.Items.Add(bit2[a]);
    }
}

listBox4 gives the following output:

false, false, true, false

now in listBox4 I think the correct output is as following because i don't change anything in bit1 array:

true, false, true, false

So what is the problem with bit1 array ?

Upvotes: 1

Views: 395

Answers (2)

MortalFool
MortalFool

Reputation: 1101

You manipualted the BitArray bit1

BitArray bit3 = bit1.And(bit2);

"Performs the bitwise AND operation on the elements in the current BitArray against the corresponding elements in the specified BitArray." MSDN

Upvotes: 3

Markus Johnsson
Markus Johnsson

Reputation: 4019

The And method mutates (i.e. alters the object) the BitArray. From documentation for the return value of BitArray.And:

[Returns] [t]he current instance containing the result of the bitwise AND operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.

Note that is says the current instance.

The bit1 array will be the same instance as the bit3 array. And as they are the same instance listBox3 and listBox4 will have the same values.

Edit: formatting and clarification

Upvotes: 3

Related Questions