简体   繁体   中英

Bitwise '&' operator

I am lacking some basic understanding in bitwise '&' operator.

5 = 101
4 = 100

So why the output of the below if condition is true cause and of bits 101 & 100 should be false :

#include <stdio.h>
main()
{
   if(5&4)
      printf("Yes\n");
}

5 is 101.

4 is 100.

5 & 4 is not 0:

101 
100 &
↓↓↓
100

Problem solved ✓


Clarification :

In C, every non-zero value satisfies the if condition. Meaning, if you write:

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

Whereas:

if (0) {
  destroyTheWorld(); // we are safe
}
5 - 101
4 - 100
5&4 - 100

It is true.

因为0b100 & 0b101等于0b100 ,而后者不等于0

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

& (Bitwise And) When inputs A and B are true, output is true; otherwise output is false

A   B   Y
---------
0 | 0 | 0
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1

| (Bitwise Or) When A or B or both inputs are true output is true; otherwise output is false

A   B   Y
---------
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 1

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

A   B   Y
---------
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0

! (Bitwise Not) Output is the opposite state of the input

A   Y
-----
0 | 1
1 | 0

Your Equation (5 & 4) == (0101 & 0100) == 0100 == 4 == true

  0101
& 0100
------
  0100
0b101 & 0b100 = 0b100

or

5&4 = 4

and 4 is non-zero and prints Yes

It enters the if condition. Because after the & operation it returns non-zero value. In C, for all non-zero value it's like returning true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM