How B change A in the bitwise expression A x B?

This article is part 2 of the series Python Bitwise Operator

How B change the A in bitwise expressions?

Suppose we have a bitwise operator x. How a bit in B changes the corresponding bit of A in the expression A x B? Can we express the bit of A x B as the corresponding bits of A based on the corresponding bit of B?

In other words, can we express the result of the of the expressions A x 0 and A x 1 as A, 0 or 1? Does the result depends on the value of A, or the result is always 0 or 1, regardless of the value of A?

So let's start answering those questions ...

AND operator: How B change A

First, Let's remind what A & B do.

The n'th bit of the result of AND operator is 1 if the corresponding bit of A is 1 AND the corresponding bit of B is 1, otherwise it's 0.

The truth table of AND
A B A & B
0 0 0
0 1 0
1 0 0
1 1 1

Let's write this truth table in a different format. In "How B changes A" format, we group together rows that has the same value of B. Then we try to express the value of A & B as A.

The "How B changes A" table of AND
A B A & B A & B as A
0 0 0 0
1 0
0 1 0 A
1 1

As we can see from the table :

  
      A & 0 = 0
      A & 1 = A
    

OR operator: How B change A

First, Let's remind what A | B do.

The n'th bit of the result of OR operator is 1 if the corresponding bit of A is 1 OR the corresponding bit of B is 1, otherwise it's 0.

The truth table of OR
A B A | B
0 0 0
0 1 1
1 0 1
1 1 1

Let's write this truth table in a different format. In "How B changes A" format, we group together rows that has the same value of B. Then we try to express the value of A | B as A.

The "How B changes A" table of OR
A B A | B A | B as A
0 0 0 A
1 1
0 1 1 1
1 1

As we can see from the table :

 
    A & 0 = A
    A & 1 = 1
    

XOR operator: How B change A

First, Let's remind what A ^ B do

The n'th bit of the result of XOR operator is 1 if the corresponding bit of A and B are different, and 0 if they are identical (if both are 0 or both are 1).

The truth table of XOR
A B A ^ B
0 0 0
0 1 1
1 0 1
1 1 0

Let's write this truth table in a different format. In "How B changes A" format, we group together rows that has the same value of B. Then we try to express the value of A ^ B as A

The "How B changes A" table of XOR
A B A ^ B A ^ B as A
0 0 0 A
1 1
0 1 1 ~A
1 0

As we can see from the table :

   
    A ^ 0 =  A
    A ^ 1 = ~A
    

Conclusions

We see "How B change A?" in the bit expression A x B for the AND, OR and XOR bitwise operators.

In the next parts, we see how those observations can help us to develop techniques to set or clear individual bit or selected group bits. We also see another significant usage of the question "How B change A": finding the status of a particular bit or selected group bits