Bitwise & operator

I lack a basic understanding of the battered '&' operator.

5 = 101 4 = 100 

So why the output below if is the true reason, and bit 101 & 100 must be false:

 #include <stdio.h> main() { if(5&4) printf("Yes\n"); } 
+7
c bitwise-operators
source share
6 answers

5 is 101

4 is 100

5 and 4 are not 0:

 101 100 & ↓↓↓ 100 

Problem resolved βœ“


Explanation

In C, every nonzero value satisfies the if condition. Value if you write:

 if(-5) { if(100) { //Reachable code } } 

While:

 if(0) { destroyTheWorld(); //We are safe } 
+17
source share
 5 - 101 4 - 100 5&4 - 100 

It's true.

+3
source share

Because 0b100 & 0b101 is 0b100 , and the latter is not 0 .

+2
source share
 0b101 & 0b100 = 0b100 

or

 5&4 = 4 

and 4 is nonzero and prints Yes

+1
source share

It is part of the if condition. Because after the & operation, it returns a nonzero value. In C, for any nonzero value, it returns true.

+1
source share

Understanding bitwise truth tables of an operator is crucial. Consider the following: where A and B are inputs and Y is an output.

& (Bitwise AND) When inputs A and B are true, the output is true; otherwise the conclusion will be false

 ABY --------- 0 | 0 | 0 0 | 1 | 0 1 | 0 | 0 1 | 1 | 1 

| (Bitwise or) When A or B or both inputs are true, true; otherwise the conclusion will be false

 ABY --------- 0 | 0 | 0 0 | 1 | 1 1 | 0 | 1 1 | 1 | 1 

^ (Bitwise X-Or) When A and B are opposite states, the output is true; otherwise the conclusion will be false

 ABY --------- 0 | 0 | 0 0 | 1 | 1 1 | 0 | 1 1 | 1 | 0 

! (Bitwise Deviation) An output is the opposite state of an input.

 AY ----- 0 | 1 1 | 0 

Your equation (5 and 4) == (0101 and 0100) == 0100 == 4 == true

  0101 & 0100 ------ 0100 
+1
source share

All Articles